#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Patch File Script
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Online patching for client system
	# - Runs from dietpi-update
	#
	# Usage:
	# - /boot/dietpi/patch_file [$G_DIETPI_VERSION_SUB]
	#////////////////////////////////////

	# Move Jessie systems to "jessie-support" branch: https://github.com/MichaIng/DietPi/issues/2332
	# - We check/apply this already via pre-patches but do as well here since older DietPi versions do not yet run pre-patches.
	# - Do not apply any further patches, restart immediately, so we don't need to think about Jessie systems when adding further patches.
	if grep -q 'jessie' /etc/os-release; then

		if grep -q '^[[:blank:]]*DEV_GITOWNER=' /boot/dietpi.txt; then

			sed -i '/^[[:blank:]]*DEV_GITBRANCH=/c\DEV_GITBRANCH=jessie-support' /boot/dietpi.txt

		else

			echo 'DEV_GITBRANCH=jessie-support' > /boot/dietpi.txt

		fi

		# Sync old code back to RAM, so no changes but "jessie-support" branch are applied
		rm -f /DietPi/.ramdisk
		if [[ -f '/boot/dietpi/func/dietpi-ramdisk' ]]; then

			/boot/dietpi/func/dietpi-ramdisk 0

		# Pre-v6.13 location
		elif [[ -f '/boot/dietpi/dietpi-ramdisk' ]]; then

			/boot/dietpi/dietpi-ramdisk 0

		fi

		# Pre-v6.22: Update Git owner due to official lead transfer from Fourdee to MichaIng: https://github.com/MichaIng/DietPi/issues/2589
		grep -q '^[[:blank:]]*DEV_GITOWNER=Fourdee' /DietPi/dietpi.txt && sed -i '/^[[:blank:]]*DEV_GITOWNER=/c\DEV_GITOWNER=MichaIng' /DietPi/dietpi.txt

		# Remove DietPi-Update and DietPi-Patch working directories to allow concurrent execution.
		cd /tmp || exit 1
		rm -Rf /tmp/DietPi-{Update,Patch}

		G_DIETPI-NOTIFY 0 'Restarting DietPi-Update to apply "jessie-support" branch...\n'

		# Failsafe: Sync changes to disk to avoid async-related issues
		sync
		sleep 3

		# Apply update forcefully, since user has already chosen to do so
		/boot/dietpi/dietpi-update 1

		G_DIETPI-NOTIFY 0 'Everything done! Terminating the obsolete DietPi-Update parent instance...\n'
		kill $PPID
		exit

	fi

	# Whether to schedue a reboot after DietPi-Update
	REBOOT=

	# Pre-v6.29: DietPi-RAMdisk removal needs to be done before loading DietPi-Globals, else /boot/dietpi still contains the old code
	if [[ -d '/DietPi' && $(readlink -f '/DietPi') != '/boot' ]]; then

		# Copy new code to disk
		cp -Rf /DietPi/* /boot/

		# Disable and remove service and mount
		systemctl disable dietpi-ramdisk
		umount -Rl /DietPi
		sed -i '/[[:blank:]]\/DietPi[[:blank:]]/d' /etc/fstab
		rm -Rf /DietPi /boot/dietpi/{,func/}dietpi-ramdisk /etc/systemd/system/dietpi-ramdisk.service

		# Create symlink for backwards compatibility
		ln -s /boot /DietPi

		# Failsafe
		sync

	fi
	# - Pre-create new DietPi runtime dir for later used scripts, created via /etc/tmpfiles.d/dietpi.conf from next boot on
	[[ -d '/run/dietpi' ]] || { mkdir -p /run/dietpi; chmod 777 /run/dietpi; }
	# - Create network info file on new location
	[[ -f '/run/dietpi/.network' ]] || { /boot/dietpi/func/obtain_network_details; chmod 666 /run/dietpi/.network; }

	# Pre-v6.22: Update Git owner due to official lead transfer from Fourdee to MichaIng: https://github.com/MichaIng/DietPi/issues/2589
	grep -q '^[[:blank:]]*DEV_GITOWNER=Fourdee' /boot/dietpi.txt && sed -i '/^[[:blank:]]*DEV_GITOWNER=/c\DEV_GITOWNER=MichaIng' /boot/dietpi.txt

	if [[ -f '/boot/dietpi/.version' ]] && grep -q '^G_GITOWNER=Fourdee' /boot/dietpi/.version; then

		sed -i '/^G_GITOWNER=/c\G_GITOWNER=MichaIng' /boot/dietpi/.version

	# Pre-v6.17: New ".version" system
	# - As loaded pre-v6.17 dietpi-update will overwrite ".version" to previous 2/3 line system, we need to rerun dietpi-update.
	elif [[ ! -f '/boot/dietpi/.version' ]] || ! grep -q '^G_GITOWNER=' /boot/dietpi/.version; then

		rm /boot/dietpi/.version

	fi

	# Pre-v6.29: Convert IMAGE_ADDITIONAL_CREDITS line to .prep_info pre-image and migrate existing HW_UUID line to new .hw_model system
	if [[ -f '/boot/dietpi/.hw_model' ]] && ! grep -q '^G_HW_UUID=' /boot/dietpi/.hw_model; then

		[[ ! -f '/boot/dietpi/.prep_info' && $(mawk 'NR==8' /boot/dietpi/.hw_model) ]] && cat << _EOF_ > /boot/dietpi/.prep_info
0
$(mawk 'NR==8' /DietPi/dietpi/.hw_model)
_EOF_
		echo "G_HW_UUID=$(mawk 'NR==5' /boot/dietpi/.hw_model)" > /boot/dietpi/.hw_model

	fi

	# Pre-v6.29: Assure that C.UTF-8 locale is available
	if ! locale -a | grep -qiE '^C.UTF-?8'; then

		apt-get -qq install --reinstall libc-bin
		# libc-bin ships C.UTF-8 as static locale already but let's add it to memory-mapped archive as well
		localedef --add-to-archive /usr/lib/locale/C.UTF-8

	fi

	# Update changed hardware IDs before dietpi-obtain_hw_model would reset them to 22
	if [[ -f '/etc/.dietpi_hw_model_identifier' ]]
	then
		G_HW_MODEL=$(</etc/.dietpi_hw_model_identifier)
		# Pre-v7.1: https://github.com/MichaIng/DietPi/pull/4193
		if [[ $G_HW_MODEL == 69 ]] # Firefly RK3399
		then
			echo 24 > /etc/.dietpi_hw_model_identifier # Generic Rockchip RK3399

		elif [[ $G_HW_MODEL == 50 || $G_HW_MODEL == 41 || $G_HW_MODEL == 3[54310] ]] # BananaPi M2+, OrangePi PC Plus, OPi Zero 2 Plus, OrangePi Plus, OrangePi Lite, OrangePi One, OrangePi PC
		then
			echo 25 > /etc/.dietpi_hw_model_identifier # Generic Allwinner H3

		elif [[  $G_HW_MODEL == 3[87] ]] # OPi PC2, OPi Prime
		then
			echo 26 > /etc/.dietpi_hw_model_identifier # Generic Allwinner H5
		fi
	fi

	# Import DietPi-Globals --------------------------------------------------------------
	/boot/dietpi/func/dietpi-obtain_hw_model # Always update
	. /boot/dietpi/func/dietpi-globals
	readonly G_PROGRAM_NAME='DietPi-Patch'
	G_INIT
	# Import DietPi-Globals --------------------------------------------------------------

	# Grab input, if given, else fallback to dietpi-globals estimation
	# - DietPi-Update includes G_VERSIONDB_SAVE after every subversion patch from v6.27 on.
	(( $1 )) && G_DIETPI_VERSION_SUB=$1

	# Pre-v6.29: Migrate newly supported SBCs from dev to master branch
	if [[ $G_DIETPI_VERSION_SUB -lt 29 && -f '/etc/.dietpi_hw_model_identifier' ]]; then

		# NanoPi M4V2 (58)
		# PINE H64 (45)
		# ROCK Pi S (73)
		if [[ $(</etc/.dietpi_hw_model_identifier) =~ ^(58|45|73)$ ]] && grep -qE '^[[:blank:]]*DEV_GITBRANCH=(dev|beta)' /boot/dietpi.txt; then

			G_DIETPI-NOTIFY 2 'Migrating from development or beta to DietPi master branch'
			G_CONFIG_INJECT 'DEV_GITBRANCH=' 'DEV_GITBRANCH=master' /boot/dietpi.txt

		fi

	fi

	# Pre-v6.20: New $G_DIETPI_INSTALL_STAGE system
	# - As loaded pre-v6.20 dietpi-update will recreate ".update_stage", we need to rerun dietpi-update.
	if [[ -f '/boot/dietpi/.update_stage' ]]; then

		G_EXEC rm /boot/dietpi/.update_stage

		if (( $G_DIETPI_INSTALL_STAGE > 0 )); then

			echo 2 > /boot/dietpi/.install_stage

		# As first run dietpi-update is executed from old dietpi-software, we need to reboot to load new first run setup scripts.
		else

			echo 0 > /boot/dietpi/.install_stage
			REBOOT=1

		fi

	fi

	# Restart DietPi-Update when not yet done, to migrate to v7
	if (( $(pgrep -c patch_file) < 2 )); then

		# Save current version to rerun patch on next launch
		# - We know the core version is 6, so store it like that, else version prior to v6.17 will default to v7: https://github.com/MichaIng/DietPi/issues/4385
		G_DIETPI_VERSION_CORE=6
		G_VERSIONDB_SAVE

		# Remove DietPi-Update and DietPi-Patch working directories to allow concurrent execution.
		G_EXEC cd /tmp
		G_EXEC rm -Rf /tmp/DietPi-{Update,Patch}

		G_DIETPI-NOTIFY 0 'Restarting DietPi-Update with new code...\n'

		# Failsafe: Sync changes to disk to avoid async-related issues
		sync
		sleep 3

		# Apply update forcefully, since user has already chosen to do so
		/boot/dietpi/dietpi-update 1

		# Reboot system if scheduled, else exit this script + parental dietpi-update only to avoid deprecated update finish
		if [[ $REBOOT == 1 ]]; then

			G_WHIP_MSG 'The system will now reboot to finish this update.'
			reboot

		else

			G_DIETPI-NOTIFY 0 'Everything done! Terminating the obsolete DietPi-Update parent instance...\n'
			kill $PPID
			exit

		fi

	fi

	#/////////////////////////////////////////////////////////////////////////////////////
	# Incremental patch system
	#/////////////////////////////////////////////////////////////////////////////////////
	# - Prevent backup prompts during patching e.g. from DietPi-Software reinstalls
	export G_PROMPT_BACKUP_DISABLED=1
	# - Prevent initial and final service control during DietPi-Software reinstalls
	export G_SERVICE_CONTROL=0

	Subversion_Patch(){

		if (( $G_DIETPI_VERSION_SUB == 0 )); then

			#-------------------------------------------------------------------------------
			# Reinstalls:
			# 	Kodi: https://github.com/MichaIng/DietPi/issues/1428
			#	Fail2Ban: https://github.com/MichaIng/DietPi/issues/1431
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && echo 31 73 >> /var/tmp/dietpi/dietpi-update_reinstalls
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 1 )); then

			#-------------------------------------------------------------------------------
			# locale rework/reset: https://github.com/MichaIng/DietPi/issues/1430#issuecomment-364763302
			[[ -f '/etc/environment' ]] && G_EXEC mv /etc/environment{,.bak}
			> /etc/environment
			/boot/dietpi/func/dietpi-set_software locale C.UTF-8
			G_WHIP_MSG '[ INFO ] Locales reset\n\nTo resolve broken locales, they have been reset to "C.UTF-8".\n\nIf you had a different locale configured on this system, please use "dietpi-config" at a later date to re-configure.\n\nIn relation to that, DietPi does not use "/etc/environment" anymore, thus it is cleaned. In case you manually edited it, a backup was created: /etc/environment.bak'
			#------------------------------------------------------------------------------
			# Removed control from DietPi-Services: https://github.com/MichaIng/DietPi/issues/1501
			systemctl enable --now dnsmasq 2> /dev/null
			systemctl enable --now openvpn 2> /dev/null
			#-------------------------------------------------------------------------------
			# https://dietpi.com/phpbb/viewtopic.php?p=10646#p10646
			[[ -f '/etc/apt/sources.list.d/openmediavault.list' ]] && rm /etc/apt/sources.list.d/openmediavault.list
			#-------------------------------------------------------------------------------
			# DietPi-Software removals: https://github.com/MichaIng/DietPi/issues/1491
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				sed -i '/^aSOFTWARE_INSTALL_STATE\[100\]=/d' /boot/dietpi/.installed # Grashopper (now PiJuice)
				sed -i '/^aSOFTWARE_INSTALL_STATE\[106\]=/d' /boot/dietpi/.installed # Raspcontrol (now NTP)
				if grep -q '^aSOFTWARE_INSTALL_STATE\[170\]=2' /boot/dietpi/.installed; then

					sed -i '/^aSOFTWARE_INSTALL_STATE\[106\]=/c\aSOFTWARE_INSTALL_STATE\[106\]=2' /boot/dietpi/.installed # NTP (replaces Raspcontrol)
					sed -i '/^aSOFTWARE_INSTALL_STATE\[170\]=/d' /boot/dietpi/.installed # NTP (now 106)

				fi

			fi
			#-------------------------------------------------------------------------------
			# Nodered lacks homedir, create it: https://github.com/MichaIng/DietPi/issues/1446#issuecomment-366370800
			if getent passwd nodered &> /dev/null && [[ ! -d '/home/nodered' ]]; then

				mkdir -p /home/nodered
				chown -R nodered:nodered /home/nodered

			fi
			#-------------------------------------------------------------------------------
			# Reinstalls:
			# v6.20	NetData 1.9
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 2 )); then

			#-------------------------------------------------------------------------------
			# Switch from rc.local to own postboot script: https://github.com/MichaIng/DietPi/issues/1376
			systemctl enable dietpi-postboot
			if [[ -f '/etc/rc.local' ]]; then

				G_WHIP_MSG 'DietPi will not use "/etc/rc.local" for its own scripts anymore.\n\nHowever, in case you manually added something, we safe a backup to "/etc/rc.local.bak", from where you can copy & paste back to the cleaned "/etc/rc.local".\n\nIt will work as before.'
				G_EXEC mv /etc/rc.local{,.bak}
				cat << '_EOF_' > /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

exit 0
_EOF_
				chmod +x /etc/rc.local

			fi
			#-------------------------------------------------------------------------------
			G_DIETPI-NOTIFY 2 'Reducing getty count and resource usage'
			systemctl mask getty-static
			#-------------------------------------------------------------------------------
			# Remove any existing apt recommends settings, before applying ours: https://github.com/MichaIng/DietPi/issues/1482#issuecomment-368031044
			rm -f /etc/apt/apt.conf.d/*recommends*
			G_EXEC eval 'cat << _EOF_ > /etc/apt/apt.conf.d/99-dietpi-norecommends
APT::Install-Recommends "false";
APT::Install-Suggests "false";
APT::AutoRemove::RecommendsImportant "false";
APT::AutoRemove::SuggestsImportant "false"; 
_EOF_'
			#-------------------------------------------------------------------------------
			# Reinstalls:
			# v6.5	Shairport Sync 3.1.7
			# 	RPi Cam
			# v6.26	Aria2 for .conf addition: https://github.com/MichaIng/DietPi/issues/1575#issuecomment-370248708
			# v6.34	Sonarr/Radarr: https://github.com/MichaIng/DietPi/issues/1566#issuecomment-369334473
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				# RPi cam pre-patch
				[[ -d '/var/www/dietpicam' ]] && G_EXEC mv /var/www/dietpicam /var/www/rpicam
				[[ -d '/mnt/dietpi_userdata/dietpicam' ]] && G_EXEC mv /mnt/dietpi_userdata/dietpicam /mnt/dietpi_userdata/rpicam
				[[ -e '/var/www/rpicam/media' ]] && G_EXEC rm -R /var/www/rpicam/media

				echo 59 >> /var/tmp/dietpi/dietpi-update_reinstalls

			fi
			#-------------------------------------------------------------------------------
			# Add certificate combining for Lighttpd to Certbot auto renewal: https://github.com/MichaIng/DietPi/pull/1553
			if [[ -f '/boot/dietpi/.dietpi-letsencrypt' ]]; then

				# Switch MinIO to new certbot.service.d/ hook:
				[[ -f '/etc/systemd/system/certbot.service' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[158\]=2' /boot/dietpi/.installed && rm /etc/systemd/system/certbot.service
				# Overall settings and config renewal, skip DietPi-Services:
				G_DIETPI_SERVICES_DISABLE=1 /boot/dietpi/dietpi-letsencrypt 1

			fi
			#-------------------------------------------------------------------------------
			# GNU key management required for some APT installs via additional repos: https://github.com/MichaIng/DietPi/issues/1388
			G_AGI dirmngr
			#-------------------------------------------------------------------------------
			# Odroids FFmpeg decendency fix: https://github.com/MichaIng/DietPi/issues/1556#issuecomment-369463910
			### Not required anymore!
			[[ $G_HW_MODEL == 1[0-5] ]] && rm -f /etc/apt/preferences.d/meveric*
			#-------------------------------------------------------------------------------
			# Subsonic 5 replaced with Airsonic: https://github.com/MichaIng/DietPi/issues/1585
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && sed -i '/^aSOFTWARE_INSTALL_STATE\[33\]=/d' /boot/dietpi/.installed
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 3 )); then

			#-------------------------------------------------------------------------------
			# Service updates: https://dietpi.com/phpbb/viewtopic.php?p=11322#p11322
			mkdir -p /var/tmp/dietpi/logs
			#-------------------------------------------------------------------------------
			# Fix microcode installation based on image creation CPU instead of image target CPU: https://github.com/MichaIng/DietPi/pull/1596
			if (( $G_HW_MODEL == 21 )); then

				if grep -qi 'vendor_id.*intel' /proc/cpuinfo; then

					dpkg-query -s amd64-microcode &> /dev/null && apt-mark auto amd64-microcode
					G_AGI intel-microcode

				elif grep -qi 'vendor_id.*amd' /proc/cpuinfo; then

					dpkg-query -s intel-microcode &> /dev/null && apt-mark auto intel-microcode
					G_AGI amd64-microcode

				fi

			fi
			#-------------------------------------------------------------------------------
			# Reinstalls
			#	UrBackupServer
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && echo 111 >> /var/tmp/dietpi/dietpi-update_reinstalls
			#-------------------------------------------------------------------------------
			# Cron minutely support: https://github.com/MichaIng/DietPi/pull/1578
			grep -q 'cron\.minutely' /etc/crontab || echo '#*/0 * * * * root cd / && run-parts --report /etc/cron.minutely' >> /etc/crontab
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 4 )); then

			#-------------------------------------------------------------------------------
			# Removal of dphys-swapfile, switch to our own swapfile control system: https://github.com/MichaIng/DietPi/issues/1602
			sed -i '/[[:space:]]dphys-swapfile[[:space:]]/d' /etc/fstab
			local swap_size swap_location
			if [[ -f '/etc/dphys-swapfile' ]]; then

				swap_size=$(sed -n '/^[[:blank:]]*CONF_SWAPSIZE=/{s/^[^=]*=//p;q}' /etc/dphys-swapfile)
				swap_location=$(sed -n '/^[[:blank:]]*CONF_SWAPFILE=/{s/^[^=]*=//p;q}' /etc/dphys-swapfile)

			fi

			G_CONFIG_INJECT 'AUTO_SETUP_SWAPFILE_SIZE=' "AUTO_SETUP_SWAPFILE_SIZE=${swap_size:-1}" /boot/dietpi.txt
			G_CONFIG_INJECT 'AUTO_SETUP_SWAPFILE_LOCATION=' "AUTO_SETUP_SWAPFILE_LOCATION=${swap_location:-/var/swap}" /boot/dietpi.txt

			# Re-Apply swap to set /tmp tmpfs size: https://github.com/MichaIng/DietPi/issues/1027#issuecomment-369435049
			# + Force auto swapfile size https://github.com/MichaIng/DietPi/issues/1593#issuecomment-371516418
			/boot/dietpi/func/dietpi-set_swapfile 1

			G_AGP dphys-swapfile
			#-------------------------------------------------------------------------------
			# Reinstalls
			# v6.20	Shairport-sync: https://github.com/MichaIng/DietPi/issues/1620#issuecomment-373086888
			# v6.23	Squeezebox server
			# v6.33	Amiberry 2.18: https://github.com/MichaIng/DietPi/issues/1410#issuecomment-374060452
			#	Mopidy: https://github.com/MichaIng/DietPi/issues/1625
			# v6.17	MPD: https://github.com/MichaIng/DietPi/issues/1614
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				killall -qw squeezeboxserver
				[[ -f '/var/lib/dietpi/dietpi-software/services/squeezeboxserver.service' ]] && rm /var/lib/dietpi/dietpi-software/services/squeezeboxserver.service
				echo 118 >> /var/tmp/dietpi/dietpi-update_reinstalls

			fi
			#-------------------------------------------------------------------------------
			# sudoers and sysctl adjustments moved to *.d/ files: https://github.com/MichaIng/DietPi/pull/1635
			echo 'dietpi ALL=NOPASSWD: ALL' > /etc/sudoers.d/dietpi
			sed -i '/dietpi/d' /etc/sudoers
			# Our config must not start with '99-' to assure priority higher than '99-sysctl.conf'
			# - New config is installed automatically via v6.9 update system.
			[[ -f '/etc/sysctl.d/99-dietpi.conf' ]] && rm /etc/sysctl.d/99-dietpi.conf
			#-------------------------------------------------------------------------------
			# RPi resolve gettext error: https://github.com/MichaIng/DietPi/issues/1631#issuecomment-373965406
			[[ -f '/etc/profile.d/wifi-country.sh' ]] && rm /etc/profile.d/wifi-country.sh
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 5 )); then

			#-------------------------------------------------------------------------------
			# RPi APT mirror fix: https://github.com/MichaIng/DietPi/issues/1659
			if (( $G_HW_MODEL < 10 )) && (( $G_RASPBIAN )); then

				G_AGDUG
				/boot/dietpi/func/dietpi-set_software apt-mirror 'http://raspbian.raspberrypi.org/raspbian/'
				G_AGUP

			fi
			#-------------------------------------------------------------------------------
			# Remove minutely running "make_nas_processes_faster" cron job, present on images with preinstalled OMV: https://github.com/MichaIng/DietPi/issues/1654
			[[ -f '/etc/cron.d/make_nas_processes_faster' ]] && rm /etc/cron.d/make_nas_processes_faster
			#-------------------------------------------------------------------------------
			# Add Dropbear ecdsa and dss host keys, if missing: https://github.com/MichaIng/DietPi/issues/1670
			command -v dropbearkey > /dev/null && [[ ! -f '/etc/dropbear/dropbear_ecdsa_host_key' ]] && dropbearkey -t ecdsa -f /etc/dropbear/dropbear_ecdsa_host_key
			#-------------------------------------------------------------------------------
			# Reinstall firmware-misc-nonfree by default (Ralink): https://github.com/MichaIng/DietPi/issues/1675
			(( $G_HW_MODEL == 21 )) || dpkg-query -s wpasupplicant &> /dev/null && G_AGI firmware-misc-nonfree
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 6 )); then

			#-------------------------------------------------------------------------------
			# Add nodered (if installed) to gpio group: https://github.com/MichaIng/DietPi/issues/1687
			getent passwd nodered &> /dev/null && usermod -aG gpio nodered
			#-------------------------------------------------------------------------------
			# Deluge systemd service update: https://github.com/MichaIng/DietPi/issues/1658
			# + Service fix for in v6.6 https://github.com/MichaIng/DietPi/issues/1689#issuecomment-379024795
			# => Fixed with reinstall on v6.21 => v6.22
			[[ -f '/var/lib/dietpi/dietpi-software/services/deluge.service' ]] && rm /var/lib/dietpi/dietpi-software/services/deluge.service
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 7 )); then

			#-------------------------------------------------------------------------------
			# Uninstalls:
			#	Removal of fbset on new installs: https://github.com/MichaIng/DietPi/issues/1716
			(( $G_DIETPI_INSTALL_STAGE == 0 )) && apt-mark auto fbset
			#-------------------------------------------------------------------------------
			# Reinstalls:
			#	XRDP: https://github.com/MichaIng/DietPi/issues/1727#issuecomment-383858979
			# v6.33	Amiberry 2.19: https://github.com/MichaIng/DietPi/issues/1707
			#	Pi-SPC
			echo 29 166 >> /var/tmp/dietpi/dietpi-update_reinstalls
			#-------------------------------------------------------------------------------
			# Pi-hole: Enable FTLDNS support by removing pihole-FTL from DietPi control: https://github.com/MichaIng/DietPi/pull/1714
			systemctl enable pihole-FTL 2> /dev/null
			#-------------------------------------------------------------------------------
			# Remove Allo Piano firmware, if not chosen as soundcard, to allow installation on demand: https://github.com/MichaIng/DietPi/issues/1656
			if { (( $G_HW_MODEL < 10 )) && ! grep -q 'allo-piano-dac' /boot/config.txt; } ||
				{ (( $G_HW_MODEL == 70 )) && ! grep -q 'allo-piano-dac' /etc/modules; }; then

				[[ -d '/lib/firmware/allo' ]] && rm -R /lib/firmware/allo

			fi
			#-------------------------------------------------------------------------------
			# RPi UART: https://github.com/MichaIng/DietPi/issues/1759
			if [[ -f '/boot/config.txt' ]]; then

				local serial_state=$(sed -n '/^[[:blank:]]*CONFIG_SERIAL_CONSOLE_ENABLE=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)
				G_CONFIG_INJECT 'enable_uart=' "enable_uart=${serial_state:-0}" /boot/config.txt

			fi
			#-------------------------------------------------------------------------------
			# Pre-create postboot dir for all systems
			mkdir -p /var/lib/dietpi/postboot.d
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 8 )); then

			#-------------------------------------------------------------------------------
			# NTP removal, switch to systemd:
			killall -qw /{DietPi,boot}/dietpi/func/run_ntpd ntpd
			G_AGP ntp
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && sed -i '/^aSOFTWARE_INSTALL_STATE\[106\]=/d' /boot/dietpi/.installed
			/boot/dietpi/func/dietpi-set_software ntpd-mode "$(sed -n '/^[[:blank:]]*CONFIG_NTP_MODE=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)"
			/boot/dietpi/func/run_ntpd
			#-------------------------------------------------------------------------------
			# Move DietPi globals and login scripts into new /etc/bashrc.d location to load on all interactive shells:
			mkdir -p /etc/bashrc.d
			# => v6.22 #G_CONFIG_INJECT '.*/etc/bashrc\.d/.*' 'for i in /etc/bashrc.d/*.sh; do [ -r "$i" ] && . $i; done' /etc/bash.bashrc
			for i in /{root,home/*}/.bashrc; do [[ -f $i ]] && sed -i '/\/DietPi/d' $i; done # Should already be removed, failsafe start clean
			rm -f /etc/profile.d/99-dietpi*
			# - Enable bash-completion for non-login shells:
			#	- NB: It is called twice on login shells then, but breaks directly if called already once.
			[[ -f '/etc/profile.d/bash_completion.sh' ]] && ln -sf /etc/profile.d/bash_completion.sh /etc/bashrc.d/dietpi-bash_completion.sh
			#-------------------------------------------------------------------------------
			# Sparky unmute fix (re: @sudeep)
			#	v2: https://github.com/MichaIng/DietPi/pull/1779
			if (( $G_HW_MODEL == 70 )) && grep -q '^[[:blank:]]*CONFIG_SOUNDCARD=usb-dac' /boot/dietpi.txt; then

				/boot/dietpi/func/dietpi-set_hardware soundcard "$(sed -n '/^[[:blank:]]*CONFIG_SOUNDCARD=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)"

			fi
			#-------------------------------------------------------------------------------
			# Reinstalls
			# v6.12	Airsonic
			# v6.23	Subsonic
			#	CAVA
			#	TigerVNC/RealVNC: https://github.com/MichaIng/DietPi/pull/1798#issuecomment-392594878
			# v6.19	Xserver: https://github.com/MichaIng/DietPi/issues/1823
			echo 28 119 120 >> /var/tmp/dietpi/dietpi-update_reinstalls
			#-------------------------------------------------------------------------------
			# Re-run set uid for sudo: https://github.com/MichaIng/DietPi/issues/794#issuecomment-392335392
			chmod 4755 "$(command -v sudo)"
			#-------------------------------------------------------------------------------
			# Removal due to changed file locations: https://github.com/MichaIng/DietPi/pull/1802
			[[ -f '/boot/dietpi/func/dietpi-set_core_environment' ]] && rm /boot/dietpi/func/dietpi-set_core_environment
			[[ -f '/var/lib/dietpi/fs_partition_resize.sh' ]] && rm /var/lib/dietpi/fs_partition_resize.sh
			[[ -f '/var/lib/dietpi/dietpi-software/services/kill-ssh-user-sessions-before-network.sh' ]] && rm /var/lib/dietpi/dietpi-software/services/kill-ssh-user-sessions-before-network.sh
			#-------------------------------------------------------------------------------
			# Offer to change global and unix user passwords to make users aware of the existance or "dietpi" and how the dietpi.txt password is used.
			# - If already installed only, else, dietpi-software will handle this on first run, after the update
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && /boot/dietpi/func/dietpi-set_software passwords

		elif (( $G_DIETPI_VERSION_SUB == 9 )); then

			#-------------------------------------------------------------------------------
			# Switch to IP commands, removal of net-tools: https://github.com/MichaIng/DietPi/pull/1839
			# - Only apply, if HomeAssistant is not installed, as it depends on net-tools: https://github.com/MichaIng/DietPi/issues/1911
			if ! [[ -f '/boot/dietpi/.installed' ]] || ! grep -q '^aSOFTWARE_INSTALL_STATE\[157\]=2' /boot/dietpi/.installed; then

				G_AGP net-tools
				G_WHIP_MSG '"net-tools" package is no longer required for DietPi systems and has been flagged as such in APT. "ifconfig" can be replaced with "ip a", or, you can reinstall "net-tools" package as needed.'

			fi
			#-------------------------------------------------------------------------------
			# Reinstalls
			# v6.19	GMrender: https://dietpi.com/phpbb/viewtopic.php?p=12985#p12985
			# v6.19	Xserver (ASUSTB GPU)
			#-------------------------------------------------------------------------------
			# DietPi-Backup rewrite, no longer supports older backups: https://github.com/MichaIng/DietPi/issues/1851
			if [[ -f '/boot/dietpi/.dietpi-backup_settings' ]]; then

				G_WHIP_MSG 'DietPi-Backup has been re-written to improve support for custom include/exclude options. It also removes the option for userdata backups, as this is now included by default.\n\nNB: Existing backups are no longer supported and cannot be restored. We highly recommend removing the older backup (eg: "rm -R /mnt/dietpi-backup"), then, create a new backup.'

			fi
			#-------------------------------------------------------------------------------
			# Fix Apache2 logging to "/error.log" instead of "/var/log/apache2/error.log": https://github.com/MichaIng/DietPi/commit/c991bd7dc579dbdc7c239e4c887b0962fa204006
			for vhost in /etc/apache2/sites-available/*.conf
			do

				[[ -e $vhost ]] || continue
				[[ -f $vhost ]] && sed -Ei '\|^[[:blank:]]*ErrorLog[[:blank:]]+/error\.log|c\	ErrorLog \$\{APACHE_LOG_DIR\}/error\.log' "$vhost"

			done
			#-------------------------------------------------------------------------------
			# Remove config.txt for non-RPi devices: https://github.com/MichaIng/DietPi/pull/1863
			(( $G_HW_MODEL > 9 )) && [[ -f '/boot/config.txt' ]] && rm /boot/config.txt
			#-------------------------------------------------------------------------------
			# Removal of NTP from dietpi-software
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && sed -i '/^aSOFTWARE_INSTALL_STATE\[106\]=/d' /boot/dietpi/.installed
			# - Cleared for roon extension manager addition
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && sed -i '/^aSOFTWARE_INSTALL_STATE\[86\]=/d' /boot/dietpi/.installed
			# - Cleared for ubooquity addition
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && sed -i '/^aSOFTWARE_INSTALL_STATE\[80\]=/d' /boot/dietpi/.installed
			# - Moode cleared
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && sed -i '/^aSOFTWARE_INSTALL_STATE\[168\]=/d' /boot/dietpi/.installed
			#-------------------------------------------------------------------------------
			# Unused and replaced with dietpi-fs_partition_resize.service
			[[ -f '/etc/systemd/system/dietpi-fs_expand.service' ]] && rm /etc/systemd/system/dietpi-fs_expand.service
			#-------------------------------------------------------------------------------
			# ASUS TB fonts broken as /usr/share/font removed but pkg's still exist, need to also do a fresh PREP on this image
			if (( $G_HW_MODEL == 52 )); then

				if (( $G_DIETPI_INSTALL_STAGE == 0 )); then

					apt-mark auto fonts-dejavu-core libfontconfig1 libfreetype6 fontconfig-config fontconfig xserver-*

				elif dpkg-query -s libfreetype6 &> /dev/null; then

					G_AGI --reinstall fonts-dejavu-core libfontconfig1 libfreetype6 fontconfig-config fontconfig

				fi

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 11 )); then

			#-------------------------------------------------------------------------------
			# Software removals:
			#	jRiver: https://github.com/MichaIng/DietPi/issues/1080#issuecomment-403489246
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && sed -i '/^aSOFTWARE_INSTALL_STATE\[148\]=/d' /boot/dietpi/.installed
			#-------------------------------------------------------------------------------
			# ASUS TB WiFi: https://github.com/MichaIng/DietPi/issues/1760
			(( $G_HW_MODEL == 52 )) && G_CONFIG_INJECT '8723bs' '8723bs' /etc/modules
			#-------------------------------------------------------------------------------
			# Software reinstalls: https://github.com/MichaIng/DietPi/issues/1877#issuecomment-403421942
			# - Items which run as own user:
			#	ympd
			# v6.17 MPD
			#	ReadyMedia (MiniDLNA)
			#	Airsonic
			# v6.18 Sonarr
			# v6.34 Radarr
			#	NZBGet
			# v6.18 RoonBridge
			#	RoonServer
			# v6.19 GMediaRender
			# v6.15 PlexPy
			#	Koel
			# v6.25 O!MPD: https://github.com/MichaIng/DietPi/issues/1934#issuecomment-406059462
			#  - NO REINSTALL: due to many changes, or, too much risk for existing user settings, fresh installs only
			# v6.33	Cuberite
			#	qBittorrent
			if (( $G_DIETPI_INSTALL_STAGE == 2 ))
			then
				if [[ ! -d '/mnt/dietpi_userdata/sonarr' && -d '/root/.config/NzbDrone' ]]
				then
					G_EXEC mkdir -p /mnt/dietpi_userdata
					G_EXEC mv /root/.config/NzbDrone /mnt/dietpi_userdata/sonarr
					G_WHIP_MSG 'INFO:\n\nSonarr userdata has been moved to the DietPi userdata directory:\n\n - /root/.config/NzbDrone > /mnt/dietpi_userdata/sonarr'
				fi
				if [[ ! -d '/mnt/dietpi_userdata/radarr' && -d '/root/.config/Radarr' ]]
				then
					G_EXEC mkdir -p /mnt/dietpi_userdata
					G_EXEC mv /root/.config/Radarr /mnt/dietpi_userdata/radarr
					G_WHIP_MSG 'INFO:\n\nRadarr userdata has been moved to the DietPi userdata directory:\n\n - /root/.config/Radarr > /mnt/dietpi_userdata/radarr'
				fi
				if [[ ! -d '/mnt/dietpi_userdata/deluge/.config/deluge' && -d '/root/.config/deluge' ]]
				then
					G_EXEC mkdir -p /mnt/dietpi_userdata/deluge/.config
					G_EXEC mv /root/.config/deluge /mnt/dietpi_userdata/deluge/.config/deluge
					G_WHIP_MSG 'INFO:\n\nDeluge userdata has been moved to the DietPi userdata directory:\n\n - /root/.config/deluge > /mnt/dietpi_userdata/deluge'
				fi
				echo 32 33 39 143 149 154 >> /var/tmp/dietpi/dietpi-update_reinstalls
			fi
			#-------------------------------------------------------------------------------
			# Increase /var/log max size to 50MB, if lower than 50MB: https://github.com/pi-hole/pi-hole/issues/2270#issuecomment-405109135
			if df | grep -q '^tmpfs.*/var/log'; then

				local var_log_size_new=50

				if (( $(sed -n '/^[[:blank:]]*AUTO_SETUP_RAMLOG_MAXSIZE=/{s/^[^=]*=//p;q}' /boot/dietpi.txt) < $var_log_size_new )); then

					G_CONFIG_INJECT 'AUTO_SETUP_RAMLOG_MAXSIZE=' "AUTO_SETUP_RAMLOG_MAXSIZE=$var_log_size_new" /boot/dietpi.txt

				fi

				sed -i '/[[:space:]]\/var\/log[[:space:]]/d' /etc/fstab
				echo "tmpfs /var/log tmpfs size=${var_log_size_new}M,noatime,lazytime,nodev,nosuid,mode=1777" >> /etc/fstab

			fi
			#-------------------------------------------------------------------------------
			# Fix Xserver uninstall issus by not purging dependencies, but leaving them for autoremove: https://github.com/MichaIng/DietPi/pull/1930/files
			local dpkg_list=$(dpkg --get-selections)
			grep -q '^xinit[[:space:]]' <<< "$dpkg_list" && apt-mark auto xauth x11-common
			grep -q '^mesa-utils-extra[[:space:]]' <<< "$dpkg_list" && apt-mark auto libgles2-mesa
			#-------------------------------------------------------------------------------
			# Removal of CurlFTPFS from dietpi-software
			[[ -f '/boot/dietpi/.installed' ]] && sed -i '/^aSOFTWARE_INSTALL_STATE\[2\]=/d' /boot/dietpi/.installed
			#-------------------------------------------------------------------------------
			# /var/lib/dietpi/dietpi-ramlog/storage moved to /var/tmp/dietpi/logs/dietpi-ramlog_store https://github.com/MichaIng/DietPi/pull/1919
			# automatically generated during ramlog, remove old location only
			[[ -d '/var/lib/dietpi/dietpi-ramlog/storage' ]] && rm -R /var/lib/dietpi/dietpi-ramlog/storage
			#-------------------------------------------------------------------------------
			# Reinstall "netbase", in case of installed NFS client and/or server, to reenable NFSv3 support: https://github.com/MichaIng/DietPi/issues/1898
			(( $G_DIETPI_INSTALL_STAGE == 2 )) &&  grep -qE '^aSOFTWARE_INSTALL_STATE\[(109|110)\]=2' /boot/dietpi/.installed && G_AGI netbase
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 12 )); then

			#-------------------------------------------------------------------------------
			# Move Koel from /var/www to /mnt/dietpi_userdata: https://github.com/MichaIng/DietPi/pull/1954
			if [[ -d '/var/www/koel' ]]; then

				G_EXEC mkdir -p /mnt/dietpi_userdata
				G_EXEC mv /var/www/koel /mnt/dietpi_userdata/koel
				G_EXEC chown -R koel:dietpi /mnt/dietpi_userdata/koel
				[[ -f '/etc/systemd/system/koel.service' ]] && sed -i 's|/var/www|/mnt/dietpi_userdata|g' /etc/systemd/system/koel.service
				G_WHIP_MSG 'INFO:\n\nKoel has been moved to the DietPi userdata directory:\n\n - /var/www/koel > /mnt/dietpi_userdata/koel'

			fi
			#-------------------------------------------------------------------------------
			# Mask systemd-logind as new default, if libpam-systemd is not installed: https://github.com/MichaIng/DietPi/issues/1767
			dpkg-query -s 'libpam-systemd' &> /dev/null || systemctl mask --now systemd-logind
			#-------------------------------------------------------------------------------
			# Disable cron.minutely, if unused to reduce cron executions and logs
			(( $(find /etc/cron.minutely/ | wc -l) > 2 )) || sed -i '\|cron\.minutely|s|^\*/[0-9]*[[:blank:]]|#*/0 |' /etc/crontab
			#-------------------------------------------------------------------------------
			# Remove "ntfs-3g" respectively "hfsplus", if no attached drive requires it.
			local fs_list=$(blkid -s TYPE -o value -c /dev/null)
			grep -q 'ntfs' <<< "$fs_list" || apt-mark auto ntfs-3g
			grep -q 'hfs' <<< "$fs_list" || apt-mark auto hfsplus
			#-------------------------------------------------------------------------------
			# Pine A64, WiFi module: https://github.com/MichaIng/DietPi/issues/1995#issuecomment-410931618
			(( $G_HW_MODEL == 40 )) && G_CONFIG_INJECT '8723bs' '8723bs' /etc/modules
			#-------------------------------------------------------------------------------
			# DietPi-Services custom includes has changed
			local fp_old='/boot/dietpi/.dietpi-services_include'
			local fp_new='/boot/dietpi/.dietpi-services_include_exclude'
			if [[ -f $fp_old ]]; then

				# Generate the new file, if not done already
				[[ -f $fp_new ]] || /boot/dietpi/dietpi-services stop cron

				# Transfer existing entries over
				while read -r line
				do

					[[ $line != '#'* ]] && echo "+ $line" >> $fp_new

				done < $fp_old

				G_WHIP_MSG "DietPi-Services custom includes has changed.\n\nYour previous items from\n - $fp_old\nhave been transfered to the new system\n - $fp_new.\n\nPlease see the new file $fp_new for more information."

				rm $fp_old

			fi
			#-------------------------------------------------------------------------------
			# NZBget UMask: https://github.com/MichaIng/DietPi/issues/1999
			[[ -f '/mnt/dietpi_userdata/nzbget/nzbget.conf' ]] && G_CONFIG_INJECT 'UMask=' 'UMask=0002' /mnt/dietpi_userdata/nzbget/nzbget.conf
			#-------------------------------------------------------------------------------
			# Assure absence of dhcpcd5, if dhclient (isc-dhcp-client) is active: https://github.com/MichaIng/DietPi/issues/1560#issuecomment-370136642
			pgrep 'dhclient' &> /dev/null && G_AGP dhcpcd5
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 13 )); then

			#-------------------------------------------------------------------------------
			# Encrypt and secure GLOBAL_PW used by DietPi-Software: https://github.com/MichaIng/DietPi/issues/2021
			if [[ ! -f '/var/lib/dietpi/dietpi-software/.GLOBAL_PW.bin' ]]; then

				G_WHIP_MSG '[ INFO ] For security reasons your global software password will be removed from dietpi.txt and instead ecrypted and saved to:
 - /var/lib/dietpi/dietpi-software/.GLOBAL_PW.bin
\nDietPi-Software will decrypt and use it as default for software installs. You can change it via:
 - dietpi-config > Security Options > Change Passwords'
 				G_EXEC mkdir -p /var/lib/dietpi/dietpi-software

				local pw_dietpi_software=$(sed -n '/^[[:blank:]]*AUTO_SETUP_GLOBAL_PASSWORD=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)
				G_EXEC sed -i '/^[[:blank:]]*AUTO_SETUP_GLOBAL_PASSWORD=/c\#AUTO_SETUP_GLOBAL_PASSWORD= # Password has been ecrypted and saved to rootfs' /boot/dietpi.txt
				[[ $pw_dietpi_software ]] || pw_dietpi_software='dietpi' # Fallback to default

				# Use new "pbkdf2" function on Buster to resolve warning about deprecated key derivation used: https://github.com/MichaIng/DietPi/issues/2213
				local pbkdf2=()
				(( $G_DISTRO > 4 )) && pbkdf2=('-iter' '10000')
				openssl enc -e -a -md sha256 -aes-256-cbc "${pbkdf2[@]}" -salt -pass pass:'DietPiRocks!' -out /var/lib/dietpi/dietpi-software/.GLOBAL_PW.bin <<< $pw_dietpi_software

				unset -v pw_dietpi_software pbkdf2

			fi
			chown root:root /var/lib/dietpi/dietpi-software/.GLOBAL_PW.bin
			chmod 600 /var/lib/dietpi/dietpi-software/.GLOBAL_PW.bin
			#-------------------------------------------------------------------------------
			# BruteFIR removal
			[[ -f '/boot/dietpi/.installed' ]] && sed -i '/^aSOFTWARE_INSTALL_STATE\[38\]=/d' /boot/dietpi/.installed
			#-------------------------------------------------------------------------------
			# Recreate machine-id: https://github.com/MichaIng/DietPi/issues/2015
			rm -f /{etc,var/lib/dbus}/machine-id
			systemd-machine-id-setup
			#-------------------------------------------------------------------------------
			# Reinstalls:
			# => v6.20 NAA: https://dietpi.com/phpbb/viewtopic.php?p=13914#p13914
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 14 )); then

			#-------------------------------------------------------------------------------
			# Reinstall fake-hwclock: https://github.com/MichaIng/DietPi/issues/2035#issuecomment-416345155
			G_AGI fake-hwclock
			#-------------------------------------------------------------------------------
			# Reinstalls:
			# v6.17 MPD: https://github.com/MichaIng/DietPi/issues/2032#issuecomment-415559451
			# v6.33	PlexPy: https://github.com/MichaIng/DietPi/issues/2047
			#-------------------------------------------------------------------------------
			# Update DietPi-Sync save file to new format
			if [[ -f '/boot/dietpi/.dietpi-sync_settings' ]] && ! grep -q '^FP_SOURCE=' /boot/dietpi/.dietpi-sync_settings; then

				cp /boot/dietpi/.dietpi-sync_settings /boot/dietpi/.dietpi-sync_settings_bk
				cat << _EOF_ > /boot/dietpi/.dietpi-sync_settings
FP_SOURCE=$(mawk 'NR==1' /boot/dietpi/.dietpi-sync_settings_bk)
FP_TARGET=$(mawk 'NR==2' /boot/dietpi/.dietpi-sync_settings_bk)
SYNC_DELETE_MODE=$(mawk 'NR==3' /boot/dietpi/.dietpi-sync_settings_bk)
SYNC_CRONDAILY=$(mawk 'NR==5' /boot/dietpi/.dietpi-sync_settings_bk)
_EOF_

			fi
			#-------------------------------------------------------------------------------
			# Preboot script addition
			systemctl enable dietpi-preboot
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 15 )); then

			#-------------------------------------------------------------------------------
			# Move to new WiFi cred array system and db store: https://github.com/MichaIng/DietPi/issues/368
			if [[ ! -f '/var/lib/dietpi/dietpi-wifi.db' ]]; then

				cat << _EOF_ > /var/lib/dietpi/dietpi-wifi.db
aWIFI_SSID[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_SSID=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_KEY[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_KEY=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_KEYMGR[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_KEYMGR=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_PROTO[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_PROTO=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_PAIRWISE[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_PAIRWISE=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_AUTH_ALG[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_AUTH_ALG=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_EAP[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_EAP=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_IDENTITY[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_IDENTITY=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_PASSWORD[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_PASSWORD=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_PHASE1[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_PHASE1=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_PHASE2[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_PHASE2=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
aWIFI_CERT[0]='$(grep -m1 '^[[:blank:]]*AUTO_SETUP_NET_WIFI_CERT=' /boot/dietpi.txt | sed 's/^[^=]*=//')'
_EOF_
				# Apply + init the remaninder of array (5) + set permissions on file
				/boot/dietpi/func/dietpi-wifidb 1

			fi
			#-------------------------------------------------------------------------------
			# Fix rare WiFi interface start issue: https://github.com/MichaIng/DietPi/issues/2074
			# shellcheck disable=SC2016
			[[ -f '/etc/network/if-pre-up.d/wireless-tools' ]] && sed -i '\|^[[:blank:]]ifconfig "$IFACE" up$|c\\t/sbin/ip link set dev "$IFACE" up' /etc/network/if-pre-up.d/wireless-tools
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 16 )); then

			#-------------------------------------------------------------------------------
			# Survey/BugReport SFTP uploads, add cert for access: https://github.com/MichaIng/DietPi/issues/2022
			# - Switch to "ssh.dietpi.com" die to Cloudflare: https://github.com/MichaIng/DietPi/issues/2022
			# - On v6.15 this was missing in PREP, thus images created meanwhile, so redo with v6.17 patch:
			mkdir -p /root/.ssh
			>> /root/.ssh/known_hosts
			sed -i '/^dietpi.com/d' /root/.ssh/known_hosts
			sed -i '/^185.101.93.93/d' /root/.ssh/known_hosts
			G_CONFIG_INJECT 'ssh.dietpi.com[[:blank:]]' 'ssh.dietpi.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDE6aw3r6aOEqendNu376iiCHr9tGBIWPgfrLkzjXjEsHGyVSUFNnZt6pftrDeK7UX+qX4FxOwQlugG4fymOHbimRCFiv6cf7VpYg1Ednquq9TLb7/cIIbX8a6AuRmX4fjdGuqwmBq3OG7ZksFcYEFKt5U4mAJIaL8hXiM2iXjgY02LqiQY/QWATsHI4ie9ZOnwrQE+Rr6mASN1BVFuIgyHIbwX54jsFSnZ/7CdBMkuAd9B8JkxppWVYpYIFHE9oWNfjh/epdK8yv9Oo6r0w5Rb+4qaAc5g+RAaknHeV6Gp75d2lxBdCm5XknKKbGma2+/DfoE8WZTSgzXrYcRlStYN' /root/.ssh/known_hosts
			#-------------------------------------------------------------------------------
			# Rock64, remove HW accell config, as its not currently functional: https://github.com/MichaIng/DietPi/issues/2086
			[[ $G_HW_MODEL == 43 && -f '/etc/X11/xorg.conf.d/20-armsoc.conf' ]] && rm /etc/X11/xorg.conf.d/20-armsoc.conf
			#-------------------------------------------------------------------------------
			# - Convert and remove old dietpi.txt entry (this includes the comment):
			if grep -q 'CONFIG_PREFER_IPVERSION' /boot/dietpi.txt; then

				grep -q '^[[:blank:]]*CONFIG_PREFER_IPVERSION=ipv4' /boot/dietpi.txt || G_CONFIG_INJECT 'CONFIG_PREFER_IPV4=' 'CONFIG_PREFER_IPV4=0' /boot/dietpi.txt
				sed -i '/CONFIG_PREFER_IPVERSION/d' /boot/dietpi.txt

			fi
			#-------------------------------------------------------------------------------
			# Update IPv6 handling: https://github.com/MichaIng/DietPi/issues/2027
			# - Advice user to re-enable IPv6 on kernel level
			if [[ ! -d '/proc/sys/net/ipv6' ]]; then

				G_WHIP_MENU_ARRAY=(

					0 ': Re-enable IPv6 on kernel level, disable via sysctl instead (Recommended)'
					1 ': Keep IPv6 disabled on kernel level, I know what I am doing!'

				)
				G_WHIP_DEFAULT_ITEM=0
				if G_WHIP_MENU '[WARNING] IPv6 is disabled via kernel module blacklist or boot cmd line.\n
This feature was previously offered via DietPi-Config and has since been removed.\n
Since more and more software requires and expects IPv6 kernel settings to be available. If you keep the current settings, this might lead to APT install errors and/or general system instability.\n
We strongly recommend you select "0 : Re-enable IPv6 on kernel level". By doing so, IPv6 will remain disabled for the interfaces at sysctl level, and, no IPv6 addresses will be assigned to your network devices.\n\nTLDR: Select option "0" :)' && (( $G_WHIP_RETURNED_VALUE == 0 )); then

					# Remove kernel module blacklisting
					[[ -f '/etc/modprobe.d/99-dietpi-blacklist-ipv6.conf' ]] && rm /etc/modprobe.d/99-dietpi-blacklist-ipv6.conf
					# Failsafe: Comment "blacklist ipv6" entries in all other sysctl config files
					local i=''
					for i in /etc/modprobe.d/*
					do

						[[ -f $i ]] && sed -i 's/^[[:blank:]]*blacklist[[:blank:]]ipv6/#&/' "$i"

					done

					# Remove boot cmd line entry
					# - RPi
					if (( $G_HW_MODEL < 10 )); then

						# Separatly remove with leading and trailing blank, since we don't know, if it's first or last argument and we must not remove both blanks
						sed -i '/^[[:blank:]]*root=/s/[[:blank:]]ipv6.disable=1//' /boot/cmdline.txt
						sed -i '/^[[:blank:]]*root=/s/ipv6.disable=1[[:blank:]]//' /boot/cmdline.txt

					# - Odroid
					elif (( $G_HW_MODEL < 20 )); then

						sed -i '/^[[:blank:]]*setenv boot/s/[[:blank:]]ipv6.disable=1//' /boot/boot.ini
						sed -i '/^[[:blank:]]*setenv boot/s/ipv6.disable=1[[:blank:]]//' /boot/boot.ini

					# - x86
					elif (( $G_HW_ARCH == 10 )); then

						sed -i '/^[[:blank:]]*GRUB_CMDLINE_LINUX_DEFAULT="/s/[[:blank:]]ipv6.disable=1//' /etc/default/grub
						sed -i '/^[[:blank:]]*GRUB_CMDLINE_LINUX_DEFAULT="/s/ipv6.disable=1[[:blank:]]//' /etc/default/grub
						update-grub

					fi

					# Disable IPv6 via sysctl
					echo -e 'net.ipv6.conf.all.disable_ipv6=1\nnet.ipv6.conf.default.disable_ipv6=1' > /etc/sysctl.d/dietpi-disable_ipv6.conf
					G_CONFIG_INJECT 'CONFIG_ENABLE_IPV6=' 'CONFIG_ENABLE_IPV6=0' /boot/dietpi.txt
					# - Do not prefer IPv4, if IPv6 is disabled anyway
					/boot/dietpi/func/dietpi-set_hardware preferipv4 0

				fi

			fi
			#-------------------------------------------------------------------------------
			# Reinstalls:
			# v6.20 MPD
			# v6.19 Chromium: Update kiosk mode autostart script: https://github.com/MichaIng/DietPi/issues/2158
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				# Run Transmission and Plex Media Server as "dietpi" group: https://github.com/MichaIng/DietPi/issues/2067#issuecomment-427579779
				if grep -q '^aSOFTWARE_INSTALL_STATE\[44\]=2' /boot/dietpi/.installed; then

					mkdir -p /etc/systemd/system/transmission-daemon.service.d
					echo -e '[Service]\nGroup=dietpi' >> /etc/systemd/system/transmission-daemon.service.d/dietpi-group.conf
					G_CONFIG_INJECT '\"umask\":' '    "umask": 7,' /etc/transmission-daemon/settings.json

				fi
				if grep -q '^aSOFTWARE_INSTALL_STATE\[42\]=2' /boot/dietpi/.installed; then

					mkdir -p /etc/systemd/system/plexmediaserver.service.d
					echo -e '[Service]\nGroup=dietpi' >> /etc/systemd/system/plexmediaserver.service.d/dietpi-group.conf

				fi

			fi
			#-------------------------------------------------------------------------------
			# Now part of rootfs: https://github.com/MichaIng/DietPi/issues/2103
			chmod +x /var/lib/dietpi/services/dietpi-wifi-monitor.sh
			#-------------------------------------------------------------------------------
			# Remove obsolete EMR patch file and redo removal of obsolete script files, as they were not removed from disk: https://github.com/MichaIng/DietPi/pull/2123#issuecomment-428121908
			rm -Rf /boot/dietpi/{.patch_emr,dietpi-{obtain_hw_model,cpu_set,ramlog,logclear,banner}}
			#-------------------------------------------------------------------------------
			# Remove www-data under sudo without PW: https://github.com/MichaIng/DietPi/issues/2121
			sed -i '/^www-data ALL=NOPASSWD: ALL/d' /etc/sudoers
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 17 )); then

			#-------------------------------------------------------------------------------
			# Remove mysql.service as we use mariadb.service, both cannot exist: https://github.com/MichaIng/DietPi/issues/1913#issuecomment-441343798
			if [[ -f '/etc/init.d/mysql' ]]; then

				G_DIETPI-NOTIFY 2 'Switching from /etc/init.d/mysql to mariadb.service'
				killall -qw mariadb mysqld # Failsafe
				systemctl disable --now mysql
				rm /etc/init.d/mysql
				update-rc.d -f mysql remove

			fi
			#-------------------------------------------------------------------------------
			# Workarounds
			# - Workaround for NanoPi Fire3 with tty1 disabled: https://github.com/MichaIng/DietPi/issues/2225
			if (( $G_HW_MODEL == 62 )) && dmesg | grep -qi 'NanoPi Fire3'; then

				chvt 2
				echo -e '#!/bin/dash\nchvt 2' > /var/lib/dietpi/postboot.d/fire3_tty2

			fi
			#-------------------------------------------------------------------------------
			# Reinstalls:
			# v6.25	OMPD: https://github.com/MichaIng/DietPi/issues/2156#issue-372201367
			# v6.25	myMPD: https://github.com/MichaIng/DietPi/issues/2156#issue-372201367
			#	RoonBridge: https://community.roonlabs.com/t/dietpi-allo-units-not-getting-the-roonbridge-b167-update-from-b164/52503/10?u=dan_knight
			# v6.34	Radarr/Lidarr/Sonarr: https://github.com/MichaIng/DietPi/issues/2219
			# v6.33	Mosquitto: https://github.com/MichaIng/DietPi/issues/2243#issuecomment-439492463
			if (( $G_DIETPI_INSTALL_STAGE == 2 ))
			then
				echo 106 121 144 >> /var/tmp/dietpi/dietpi-update_reinstalls
				# - Switch to "mariadb" systemd service on Stretch+: https://github.com/MichaIng/DietPi/pull/2196
				if grep -q '^aSOFTWARE_INSTALL_STATE\[88\]=2' /boot/dietpi/.installed
				then
					G_WHIP_MSG '[ INFO ] Switch from "mysql" to "mariadb" service
\nOn Stretch (and above) systems, DietPi-Services will use the pre-installed "mariadb" systemd service now, instead of the obsolete "mysql" init.d service.
\nYou will not face any practical differences, since both services start the same MariaDB binary. In case you manually want to handle the service, use "systemctl start|stop|restart mariadb" from now on.'
				fi
			fi
			#-------------------------------------------------------------------------------
			# systemd-logind required for shutdown options: https://github.com/MichaIng/DietPi/issues/2155#issuecomment-437702869
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[31\]=2' /boot/dietpi/.installed && systemctl unmask systemd-logind
			#-------------------------------------------------------------------------------
			# Patch Odroid LCD: https://github.com/MichaIng/DietPi/issues/2256
			[[ -f '/etc/systemd/system/odroid-lcd35.service' ]] && /boot/dietpi/func/dietpi-set_hardware lcdpanel odroid-lcd35
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 18 )); then

			#-------------------------------------------------------------------------------
			# Conf renaming: https://github.com/MichaIng/DietPi/pull/2312/files
			# - Apache
			if [[ -f '/etc/apache2/sites-available/owncloud.conf' ]]; then

				a2dissite owncloud
				mv /etc/apache2/sites-available/owncloud.conf /etc/apache2/sites-available/dietpi-owncloud.conf

			fi
			if [[ -f '/etc/apache2/sites-available/nextcloud.conf' ]]; then

				a2dissite nextcloud
				mv /etc/apache2/sites-available/nextcloud.conf /etc/apache2/sites-available/dietpi-nextcloud.conf

			fi
			if [[ -f '/etc/apache2/sites-available/rutorrent.conf' ]]; then

				a2dissite rutorrent
				mv /etc/apache2/sites-available/rutorrent.conf /etc/apache2/sites-available/dietpi-rutorrent.conf
				a2ensite dietpi-rutorrent

			fi
			# - Nginx
			[[ -f '/etc/nginx/sites-dietpi/owncloud.config' ]] && mv /etc/nginx/sites-dietpi/owncloud.config /etc/nginx/sites-dietpi/dietpi-owncloud.conf
			[[ -f '/etc/nginx/sites-dietpi/nextcloud.config' ]] && mv /etc/nginx/sites-dietpi/nextcloud.config /etc/nginx/sites-dietpi/dietpi-nextcloud.conf
			[[ -f '/etc/nginx/sites-dietpi/rutorrent.config' ]] && mv /etc/nginx/sites-dietpi/rutorrent.config /etc/nginx/sites-dietpi/dietpi-rutorrent.conf
			#	- Failsafe and custom entries
			for i in /etc/nginx/sites-dietpi/*.config
			do

				[[ -f $i ]] || break
				mv "$i" "${i%ig}"

			done
			#	- Apply to Nginx vhost
			#	- Move to v6.19 => v6.20 patch for users, which update directly from v6.19.5 to v6.20
			#grep -q 'include /etc/nginx/sites-dietpi/\*\.config;' /etc/nginx/sites-available/default &> /dev/null && G_CONFIG_INJECT 'include /etc/nginx/sites-dietpi/\*\.config;' 'include /etc/nginx/sites-dietpi/*.conf;' /etc/nginx/sites-available/default
			# - Kodi input rules
			[[ -f '/etc/udev/rules.d/99-input.rules' ]] && mv /etc/udev/rules.d/99-input.rules /etc/udev/rules.d/99-dietpi-kodi.rules
			#-------------------------------------------------------------------------------
			# Asus TB 2.0.8 image, fix corrupt characters in desktops
			if (( $G_HW_MODEL == 52 )) && dpkg --get-selections | grep -q 'fonts-dejavu-core'; then

				G_AGI --reinstall libfreetype6 fonts-dejavu-core
				G_EXEC fc-cache -r -v

			fi
			#-------------------------------------------------------------------------------
			# Switch to udev rule for WiFi powersaving disable
			rm -f /etc/systemd/system/wifi_disable_powersave.service*
			#-------------------------------------------------------------------------------
			# - Reinstalls
			#	Chromium: https://github.com/MichaIng/DietPi/issues/2298
			# v6.27	Allo GUI: https://github.com/MichaIng/DietPi/issues/2305
			# v6.27	GMrender: Due to Allo GUI service enable failure.
			#	Xorg: XU4 conf
			# v6.23	Pydio: https://github.com/MichaIng/DietPi/issues/2308
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && echo 6 113 >> /var/tmp/dietpi/dietpi-update_reinstalls
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 19 )); then

			#-------------------------------------------------------------------------------
			# rpi-update drop support info
			if command -v rpi-update > /dev/null && G_WHIP_YESNO '[ INFO ] RPi-Update detected\n\nIn our effort to improve system stability, and, offer software installations which build custom modules (eg: WireGuard), we can no longer support systems with non-stock-APT kernel installed (eg: rpi-update).\n\nWould you like to revert to the APT kernel now, ensuring stability and official DietPi system support?'; then

				local arpi_firmware=('raspberrypi-bootloader' 'raspberrypi-kernel' 'libraspberrypi-bin' 'libraspberrypi0')
				G_AGP rpi-update
				command -v rpi-source > /dev/null && rm "$(command -v rpi-source)"
				G_AGI --reinstall "${arpi_firmware[@]}"
				apt-mark unhold "${arpi_firmware[@]}"

			fi
			#-------------------------------------------------------------------------------
			# Apply Nginx vhost patch: https://github.com/MichaIng/DietPi/pull/2327
			#	- Moved from v6.18 => v6.19 patch for users, which update directly from v6.19.5 to v6.20
			grep -q 'include /etc/nginx/sites-dietpi/\*\.config;' /etc/nginx/sites-available/default &> /dev/null && G_CONFIG_INJECT 'include /etc/nginx/sites-dietpi/\*\.config;' 'include /etc/nginx/sites-dietpi/*.conf;' /etc/nginx/sites-available/default
			#-------------------------------------------------------------------------------
			# Migrate Blynk to new dir structure: https://github.com/MichaIng/DietPi/issues/2322
			if (( $G_DIETPI_INSTALL_STAGE == 2 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[131\]=2' /boot/dietpi/.installed &&
				[[ -d '/mnt/dietpi_userdata/blynk' && ! -d '/mnt/dietpi_userdata/blynk/data' ]]; then

				G_EXEC mv /mnt/dietpi_userdata/blynk /mnt/dietpi_userdata/blynk_bak
				G_EXEC mv /etc/blynkserver /mnt/dietpi_userdata/blynk
				G_EXEC mv /mnt/dietpi_userdata/blynk/server.jar /mnt/dietpi_userdata/blynk/blynkserver.jar
				G_EXEC mv /mnt/dietpi_userdata/blynk_bak/server.properties /mnt/dietpi_userdata/blynk/
				G_EXEC mv /mnt/dietpi_userdata/blynk_bak /mnt/dietpi_userdata/blynk/data
				G_CONFIG_INJECT 'data.folder=' 'data.folder=/mnt/dietpi_userdata/blynk/data' /mnt/dietpi_userdata/blynk/server.properties

			fi
			#-------------------------------------------------------------------------------
			# Grafana: Remove obsolete x86_64 APT source, reinstall below to apply official repo: https://github.com/MichaIng/DietPi/issues/2449
			rm -f /etc/apt/sources.list.d/grafana*.list
			#-------------------------------------------------------------------------------
			# - Reinstalls
			#	Blynk: Apply new run user, update binary (jar)
			# v6.22	Deluge: https://github.com/MichaIng/DietPi/issues/2339
			#	Netdata: https://github.com/MichaIng/DietPi/pull/2337
			#	NAA Daemon: https://github.com/MichaIng/DietPi/issues/2387#issue-395321320
			#	MPD: https://github.com/MichaIng/DietPi/issues/2377
			#	Samba: https://github.com/MichaIng/DietPi/issues/2396#issuecomment-451701569
			# v6.33	Amiberry 2.24
			#	Shairport Sync: https://github.com/MichaIng/DietPi/issues/2439
			# v6.27	Grafana: https://github.com/MichaIng/DietPi/issues/2449
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				echo 37 65 124 128 131 >> /var/tmp/dietpi/dietpi-update_reinstalls

				# Samba: Link disk cache to RAM: https://github.com/MichaIng/DietPi/issues/2396
				if grep -q '^aSOFTWARE_INSTALL_STATE\[96\]=2' /boot/dietpi/.installed; then

					rm -Rf /var/cache/samba
					mkdir -p /run/samba-cache
					ln -s /run/samba-cache /var/cache/samba
					echo 'd /run/samba-cache' > /etc/tmpfiles.d/dietpi-samba_cache.conf

				fi

			fi
			#-------------------------------------------------------------------------------
			# DietPi file renaming/removal:
			# - autologin.conf: https://github.com/MichaIng/DietPi/pull/2343
			[[ -f '/etc/systemd/system/getty@tty1.service.d/autologin.conf' ]] && mv /etc/systemd/system/getty@tty1.service.d/autologin.conf /etc/systemd/system/getty@tty1.service.d/dietpi-autologin.conf
			# - README.md: https://github.com/MichaIng/DietPi/pull/2341
			[[ -f '/boot/README.md' ]] && mv /boot/README.md /boot/dietpi-README.md
			# - kill-ssh-user-sessions-before-network: https://github.com/MichaIng/DietPi/pull/2357/commits/c8eb15c169cfaba69fec0b3e631e2241e0bdb7d5
			systemctl disable kill-ssh-user-sessions-before-network 2> /dev/null
			[[ -f '/etc/systemd/system/kill-ssh-user-sessions-before-network.service' ]] && rm /etc/systemd/system/kill-ssh-user-sessions-before-network.service
			[[ -f '/var/lib/dietpi/services/kill-ssh-user-sessions-before-network.sh' ]] && rm /var/lib/dietpi/services/kill-ssh-user-sessions-before-network.sh
			systemctl enable dietpi-kill_ssh
			# - dietpi-unsupported_terminal.sh: https://github.com/MichaIng/DietPi/issues/2347
			[[ -f '/etc/profile.d/dietpi-unsupported_terminal.sh' ]] && rm /etc/profile.d/dietpi-unsupported_terminal.sh
			# - Possible leftover from PREP:
			[[ -f '/boot/dietpi/pre-patch_file' ]] && rm /boot/dietpi/pre-patch_file
			# - dietpi/conf removal: https://github.com/MichaIng/DietPi/pull/2393
			[[ -d '/boot/dietpi/conf' ]] && rm -R /boot/dietpi/conf
			#-------------------------------------------------------------------------------
			#.dietpi-autostart_index removal, if zero: https://github.com/MichaIng/DietPi/pull/2343
			[[ -f '/boot/dietpi/.dietpi-autostart_index' ]] && (( $(</boot/dietpi/.dietpi-autostart_index) == 0 )) && rm /boot/dietpi/.dietpi-autostart_index
			#-------------------------------------------------------------------------------
			# Disable coturn logging for existing installs: https://github.com/MichaIng/DietPi/pull/2333
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[168\]=2' /boot/dietpi/.installed && G_CONFIG_INJECT 'DAEMON_ARGS=' "DAEMON_ARGS='-c /etc/turnserver.conf -o -l stdout --no-stdout-log --simple-log'" /etc/default/coturn
			#-------------------------------------------------------------------------------
			# Remove nofail and x-systemd.automount option from /boot mount: https://github.com/MichaIng/DietPi/pull/2357#issuecomment-449177715
			sed -i '\|[[:blank:]]/boot[[:blank:]]|s|,x-systemd.automount||' /etc/fstab
			sed -i '\|[[:blank:]]/boot[[:blank:]]|s|,nofail||' /etc/fstab
			#-------------------------------------------------------------------------------
			# Re-enable owncloud/Nextcloud Apache configs, to fix faulty v6.19 installs: https://github.com/MichaIng/DietPi/pull/2361/commits/e33ca150cf29a4f278f5df2defc495053700a91e
			[[ -f '/etc/apache2/sites-available/dietpi-owncloud.conf' ]] && a2ensite dietpi-owncloud
			[[ -f '/etc/apache2/sites-available/dietpi-nextcloud.conf' ]] && a2ensite dietpi-nextcloud
			#-------------------------------------------------------------------------------
			# Clear install state for Medusa
			[[ $G_DIETPI_INSTALL_STAGE == 2 && ! -d '/mnt/dietpi_userdata/medusa' ]] && sed -i '/^aSOFTWARE_INSTALL_STATE\[116\]=/d' /boot/dietpi/.installed
			# - Inform user about SickRage being replaced by Medusa
			if [[ -d '/etc/sickrage' || -d '/mnt/dietpi_userdata/sickrage' ]]; then

				G_WHIP_MSG '[WARNING] We found an existing SickRage install on your system\n
We already dropped SickRage from DietPi-Software install options with v6.18, now it has been fully replaced with "Medusa", an older stabilized fork.
DietPi will still handle your SickRage service and directory permissions, but this might change soon.\n
We encourage everyone to use Medusa instead. There are guides for migrating your SickRage TV shows and settings, but the most general advice is to do a fresh install of Medusa: dietpi-software install 116\n
Also have a look at "Sonarr", another alternative TV show manager, available for install via DietPi-Software.'

			fi
			#-------------------------------------------------------------------------------
			# Remove obsolete flags: https://github.com/MichaIng/DietPi/pull/2398#issuecomment-452398770
			[[ -f '/var/lib/dietpi/.G_RPI_UPDATE' ]] && rm /var/lib/dietpi/.G_RPI_UPDATE
			# https://github.com/MichaIng/DietPi/pull/2407/commits/5b7ad8bddc9dd5ffe89a2614615eb936333c8d41
			[[ -f '/var/lib/dietpi/.compiled_i-sabre-k2m' ]] && rm /var/lib/dietpi/.compiled_i-sabre-k2m
			#-------------------------------------------------------------------------------
			# RPi changes: https://github.com/MichaIng/DietPi/pull/2402
			if (( $G_HW_MODEL < 10 )); then

				# Remove/Replace obsolete config.txt settings
				sed -i 's/display_rotate/display_hdmi_rotate/' /boot/config.txt
				sed -i '/disable_pvt/d' /boot/config.txt
				sed -i '/avoid_pwm_pll/d' /boot/config.txt

				# Remove doubled AUTO_SETUP_HEADLESS entry, introduced with Beta v6.20.2
				if (( $(grep -c '^[[:blank:]]*AUTO_SETUP_HEADLESS=' /boot/dietpi.txt) > 1 )); then

					# Last match is the correct one, added by "dietpi-set_hardware headless 1"
					local current=$(grep '^[[:blank:]]*AUTO_SETUP_HEADLESS=' /boot/dietpi.txt | tail -1 | sed 's/^[^=]*=//')
					sed -i '/^[[:blank:]]*AUTO_SETUP_HEADLESS=/d' /boot/dietpi.txt
					echo "AUTO_SETUP_HEADLESS=$current" >> /boot/dietpi.txt

				fi

				# Apply new headless mode method, if set
				grep -q '^[[:blank:]]*CONFIG_HDMI_OUTPUT=0' /boot/dietpi.txt && /boot/dietpi/func/dietpi-set_hardware headless 1

				# Renamed to: AUTO_SETUP_HEADLESS (added by verify_dietpi.txt automatically)
				sed -i '/CONFIG_HDMI_OUTPUT/d' /boot/config.txt

			fi
			#-------------------------------------------------------------------------------
			# Buster: "systemd" does not depend on "procps" anymore, thus we need to set it manually installed, simply applied on all distro versions.
			G_AGI procps
			#-------------------------------------------------------------------------------
			# Remove wireless-power setting from /etc/network/interfaces, if not supported by adapter/firmware: https://github.com/MichaIng/DietPi/issues/2198
			iwconfig "wlan$(mawk 'NR==2' /run/dietpi/.network)" power off &> /dev/null || sed -i '/^wireless-power/d' /etc/network/interfaces
			#-------------------------------------------------------------------------------
			# Remove armbian banner/profiles left on ASUS TB image
			rm -f /etc/profile.d/armbian-*
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 20 )); then

			#-------------------------------------------------------------------------------
			# Image updates
			if [[ $G_HW_MODEL == 4[0234] && ! -f '/etc/armbian-release' ]]; then

				G_WHIP_MSG "[ INFO ] The base image for $G_HW_MODEL_NAME has been updated.\n\nPlease reinstall your system with the latest image from https://dietpi.com#download.\n\nYou can continue to use this existing installation, however, some kernel features may not be available."

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 21 )); then

			#-------------------------------------------------------------------------------
			# Redo our /etc/bash.bashrc entry, user confirmed 4 entries: https://github.com/MichaIng/DietPi/issues/2529
			# As well allow ".bash" file ending and remove obsolete dietpi-*.sh scripts: https://github.com/MichaIng/DietPi/pull/2636
			sed -i '\#for i in /etc/bashrc#d' /etc/bash.bashrc
			# shellcheck disable=SC2016
			G_CONFIG_INJECT '.*/etc/bashrc\.d/.*' 'for i in /etc/bashrc.d/*.sh /etc/bashrc.d/*.bash; do [ -r "$i" ] && . $i; done' /etc/bash.bashrc
			rm -f /etc/bashrc.d/dietpi-*.sh
			#-------------------------------------------------------------------------------
			# Mopidy fix: https://github.com/MichaIng/DietPi/issues/2536
			getent passwd mopidy > /dev/null && usermod -aG dietpi,audio -d /mnt/dietpi_userdata/mopidy mopidy
			#-------------------------------------------------------------------------------
			# Removed dependency on "p7zip-full", use "7zr" (p7zip) instead: https://github.com/MichaIng/DietPi/pull/2559
			G_AGI p7zip
			if dpkg-query -s p7zip-full &> /dev/null &&
				! G_WHIP_BUTTON_OK_TEXT='Yes' G_WHIP_BUTTON_CANCEL_TEXT='No' G_WHIP_YESNO '[QUESTION] Do you want to keep "p7zip-full"?\n
DietPi does not require the "p7zip-full" package anymore but just "p7zip" instead.
- "p7zip" provides the lightweight standalone "7zr" command to handle 7zip archives only.
- "p7zip-full" additionally provides the "7z" and "7za" commands which can handle other archive types as well.
  However, DietPi internally uses "unzip", "tar" and "unrar" to handle those.\n
Do you still want to keep "p7zip-full"?'; then

				apt-mark auto p7zip-full
				G_AGA

			fi
			#-------------------------------------------------------------------------------
			# Fix Pi-hole permissions to allow "pihole -up"
			if [[ -d '/var/www/html/pihole' && -d '/var/www/html/admin' ]]; then

				G_EXEC cd /var/www/html/admin
				git reset --hard HEAD
				G_EXEC cd /tmp/$G_PROGRAM_NAME

			fi
			#-------------------------------------------------------------------------------
			# MPD: Fix permissions issue: https://github.com/MichaIng/DietPi/issues/2462
			if [[ -f '/etc/mpd.conf' ]]; then

				sed -Ei '/^(user|group)[[:blank:]]/d' /etc/mpd.conf
				sed -i '/^Group=/d' /lib/systemd/system/mpd.service
				G_CONFIG_INJECT 'User=' 'User=mpd' /lib/systemd/system/mpd.service '\[Service\]'
				G_CONFIG_INJECT 'PermissionsStartOnly=' 'PermissionsStartOnly=true' /lib/systemd/system/mpd.service '^User=mpd'
				usermod -aG audio,dietpi mpd

			fi
			#-------------------------------------------------------------------------------
			# Fix rc-local.service from old images to match new systemd-rc-local-generator: https://github.com/MichaIng/DietPi/issues/2566
			systemctl disable rc-local rc.local
			grep -q 'dietpi' /lib/systemd/system/rc-local.service && cat << _EOF_ > /lib/systemd/system/rc-local.service
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.local
After=network.target

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no
_EOF_
			#-------------------------------------------------------------------------------
			# Remove obsolete DietPi-Sync log: https://github.com/MichaIng/DietPi/pull/2606
			[[ -f '/var/log/dietpi-sync.log' ]] && rm /var/log/dietpi-sync.log
			#-------------------------------------------------------------------------------
			# XU4, use Meveric's xorg.conf which detects 3.x and 4.x kernel configuration requirments:
			if [[ $G_HW_MODEL == 11 && -f '/etc/X11/xorg.conf' ]]; then

				rm /etc/X11/xorg.conf
				G_AGI --reinstall firmware-samsung xf86-video-armsoc-odroid malit628-odroid

			fi
			#-------------------------------------------------------------------------------
			# RPi | Remove "framebuffer_depth" handling: https://github.com/MichaIng/DietPi/pull/2635
			(( $G_HW_MODEL < 10 )) && sed -i '/framebuffer_depth/d' /boot/config.txt
			#-------------------------------------------------------------------------------
			# Nextcloud: Add OCM/OCS provider redirects as this is checked and printed as warning on admin panel: https://github.com/MichaIng/DietPi/issues/2638
			if [[ -f '/etc/apache2/sites-available/dietpi-nextcloud.conf' ]] &&
				! grep -q 'oc[ms]-provider' /etc/apache2/sites-available/dietpi-nextcloud.conf; then

				echo 'Redirect permanent /ocm-provider /nextcloud/ocm-provider
Redirect permanent /ocs-provider /nextcloud/ocs-provider' >> /etc/apache2/sites-available/dietpi-nextcloud.conf

			fi
			if [[ -f '/etc/lighttpd/conf-available/99-dietpi-nextcloud.conf' ]] &&
				! grep -q 'oc[ms]-provider' /etc/lighttpd/conf-available/99-dietpi-nextcloud.conf; then

				echo 'url.redirect += (
	"^/ocm-provider" => "/nextcloud/ocm-provider",
	"^/ocs-provider" => "/nextcloud/ocs-provider"
)' >> /etc/lighttpd/conf-available/99-dietpi-nextcloud.conf

			fi
			if [[ -f '/etc/nginx/sites-dietpi/dietpi-nextcloud.conf' ]] && ! grep -q 'oc[ms]-provider' /etc/nginx/sites-dietpi/dietpi-nextcloud.conf; then

				# shellcheck disable=SC2016
				echo 'location ~ ^\/(?:ocm-provider|ocs-provider).* {
	rewrite ^ /nextcloud$request_uri;
}' >> /etc/nginx/sites-dietpi/dietpi-nextcloud.conf

			fi
			#-------------------------------------------------------------------------------
			# Reinstalls
			# v6.33	Amiberry 2.25: https://github.com/MichaIng/DietPi/issues/2599
			# v6.27	Allo GUI v13: https://github.com/sparky-sbc/sparky-test/tree/master/dietpi-gui-usbdebug
			#	Deluge: Patch according to installer rework: https://github.com/MichaIng/DietPi/pull/2594
			#	rTorrent: https://github.com/MichaIng/DietPi/issues/2629
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				local reinstall_indices=

				if [[ -f '/root/.rtorrent.rc' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[107\]=2' /boot/dietpi/.installed; then

					reinstall_indices+=' 107'
					G_CONFIG_INJECT 'system.umask.set[[:blank:]=]' 'system.umask.set = 002' /root/.rtorrent.rc
					G_EXEC mkdir -p /mnt/dietpi_userdata/rtorrent
					G_EXEC mv /root/.rtorrent.rc /mnt/dietpi_userdata/rtorrent/

				fi

				if grep -q '^aSOFTWARE_INSTALL_STATE\[45\]=2' /boot/dietpi/.installed && getent passwd deluge > /dev/null; then # Only do this once, regardless of re-patches

					reinstall_indices+=' 45'

					G_AGP deluge-webui
					G_EXEC mkdir -p /var/log/deluged /mnt/dietpi_userdata
					[[ -e ~deluge ]] && G_EXEC mv ~deluge /mnt/dietpi_userdata/deluge_home_backup
					G_EXEC userdel -rf deluge
					G_EXEC rm -Rf /{root,home/*}/.config/deluge
					[[ -f '/var/log/deluged.log' ]] && G_EXEC mv /var/log/deluged.log /var/log/deluged/daemon.log
					[[ -f '/var/log/deluge-web.log' ]] && G_EXEC mv /var/log/deluge-web.log /var/log/deluged/web.log

					G_WHIP_MSG '[ INFO ] Deluge rework\n
Our Deluge installer has been reworked to match Debian APT package defaults and official documentations. This also resolves an issue when attempting to access "deluge-console".
- It runs now as user "debian-deluged".
- The user "deluge" has been removed, its home directory has been backed up to:
    /mnt/dietpi_userdata/deluge_home_backup
  in case it existed.
- Logs have been moved to /var/log/deluged/daemon.log|web.log.
- Apart from that, all your settings and data have been preserved.\n
NB: When accessing "deluge-console" you need to do that as user "debian-deluged":
    sudo -u debian-deluged deluge-console'

				fi

				echo "$reinstall_indices" >> /var/tmp/dietpi/dietpi-update_reinstalls

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 22 )); then

			#-------------------------------------------------------------------------------
			# Apply Serial/UART rework: https://github.com/MichaIng/DietPi/pull/2678
			# - Cleanup: Remove serial-getty masks for all non-existent serial devices
			for i in /etc/systemd/system/serial-getty@tty{S,AMA,SAC}[0-9].service
			do

				[[ -L $i && $(readlink "$i") == '/dev/null' ]] || continue
				local tty=${i##*serial-getty@}
				tty=${tty%.service}
				[[ -e /dev/$tty ]] || systemctl unmask "serial-getty@$tty"

			done
			# - Fix: Disable serial-getty instances for all non-existent serial devices
			for i in /etc/systemd/system/getty.target.wants/serial-getty@tty{S,AMA,SAC}[0-9].service
			do

				[[ -L $i ]] || continue
				local tty=${i##*serial-getty@}
				tty=${tty%.service}
				[[ -e /dev/$tty ]] || systemctl disable "serial-getty@$tty"

			done
			#-------------------------------------------------------------------------------
			# Patch proxy settings changes: https://github.com/MichaIng/DietPi/pull/2716
			sed -i '/^[[:blank:]]*CONFIG_PROXY_ENABLED=/d' /boot/dietpi.txt
			local proxy=''
			if proxy=$(grep '^[[:blank:]]*export {http,https,ftp}_proxy=' /etc/bash.bashrc); then

				[[ -f '/etc/bashrc.d/dietpi-proxy.sh' ]] || echo "$proxy" > /etc/bashrc.d/dietpi-proxy.sh
				sed -i '/^[[:blank:]]*export {http,https,ftp}_proxy=/d' /etc/bash.bashrc

			fi
			#-------------------------------------------------------------------------------
			# dietpi-set_dphys-swapfile renamed to: "dietpi-set_swapfile": https://github.com/MichaIng/DietPi/pull/2720
			[[ -f '/boot/dietpi/func/dietpi-set_dphys-swapfile' ]] && rm /boot/dietpi/func/dietpi-set_dphys-swapfile
			#-------------------------------------------------------------------------------
			# Remove obsolete OpenJDK APT preferences on Jessie: https://github.com/MichaIng/DietPi/pull/2753
			[[ -f '/etc/apt/preferences.d/99-dietpi-openjdk-8-jdk' ]] && rm /etc/apt/preferences.d/99-dietpi-openjdk-8-jdk
			#-------------------------------------------------------------------------------
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				# Infom Sonarr/Radarr/Lidarr users about DietPi-Arr_to_RAM: https://github.com/MichaIng/DietPi/pull/2698
				grep -qE '^aSOFTWARE_INSTALL_STATE\[(106|144|145)\]=2' /boot/dietpi/.installed && G_WHIP_MSG 'DietPi-Arr_to_RAM | Link Sonarr/Radarr/Lidarr database files to RAM\n
With v6.18 we silently added a new script that allows linking Sonarr/Radarr/Lidarr database files to RAM, increasing access performance, reducing disk I/O and avoiding constant external HDD spinning due to the very regular access to these files.\n
This script has gone through some rework and polishing with v6.23 and can now be enabled to automatically link those databases to RAM on boot and store them back to disk on shutdown.\n
Further info and usage: https://dietpi.com/phpbb/viewtopic.php?t=5828'
				#-----------------------------------------------------------------------
				# Fix IPv6 connections with WireGuard: https://github.com/MichaIng/DietPi/issues/2691
				if [[ -f '/etc/wireguard/wg0.conf' ]] && ! grep -q 'sysctl' /etc/wireguard/wg0.conf; then

					[[ -f '/etc/sysctl.d/dietpi-wireguard.conf' ]] && rm /etc/sysctl.d/dietpi-wireguard.conf
					# shellcheck disable=SC2016
					sed -i '/^ListenPort/a\PostUp = sysctl net.ipv4.conf.%i.forwarding=1 net.ipv4.conf.$(mawk "NR==3" /run/dietpi/.network).forwarding=1' /etc/wireguard/wg0.conf
					# shellcheck disable=SC2016
					sed -i '/^ListenPort/a\PostUp = sysctl net.ipv6.conf.$(mawk "NR==3" /run/dietpi/.network).accept_ra=2' /etc/wireguard/wg0.conf
					# shellcheck disable=SC2016
					sed -i '/^ListenPort/a\PostUp = sysctl net.ipv6.conf.%i.forwarding=1 net.ipv6.conf.$(mawk "NR==3" /run/dietpi/.network).forwarding=1' /etc/wireguard/wg0.conf
					# shellcheck disable=SC2016
					sed -i '/^ListenPort/a\PostUp = ip6tables -A FORWARD -i %i -j ACCEPT; ip6tables -t nat -A POSTROUTING -o $(mawk "NR==3" /run/dietpi/.network) -j MASQUERADE' /etc/wireguard/wg0.conf
					# shellcheck disable=SC2016
					sed -i '/^ListenPort/a\PostDown = ip6tables -D FORWARD -i %i -j ACCEPT; ip6tables -t nat -D POSTROUTING -o $(mawk "NR==3" /run/dietpi/.network) -j MASQUERADE' /etc/wireguard/wg0.conf

				fi
				#-----------------------------------------------------------------------
				# NordVPN: Tiny fix for doubled auth-user-pass entry: https://github.com/MichaIng/DietPi/commit/847a016638c6929153dc16e7ce054d3dce5e4c60
				if [[ -f '/var/lib/dietpi/dietpi-software/installed/dietpi-nordvpn/settings_dietpi.conf' ]]; then

					. /var/lib/dietpi/dietpi-software/installed/dietpi-nordvpn/settings_dietpi.conf
					if [[ -f /etc/openvpn/ovpn_$PROTOCOL/$NORDVPN_SERVER && $(grep -c '^auth-user-pass' "/etc/openvpn/ovpn_$PROTOCOL/$NORDVPN_SERVER") == 2 ]]; then

						sed -i '/^auth-user-pass$/d' "/etc/openvpn/ovpn_$PROTOCOL/$NORDVPN_SERVER"

					fi
					unset -v NORDVPN_USERNAME NORDVPN_PASSWORD NORDVPN_SERVER PROTOCOL

				fi
				#-----------------------------------------------------------------------
				# Remove obsolete "bluetooth" meta package and mark bluez instead
				if dpkg-query -s bluetooth &> /dev/null; then

					apt-mark manual bluez
					apt-mark auto bluetooth
					G_AGA

				fi
				#-----------------------------------------------------------------------
				# Add /etc/network/interfaces.d/ drop-in config support
				grep -q 'interfaces\.d' /etc/network/interfaces || sed -i '1i\source interfaces.d/*' /etc/network/interfaces
				#-----------------------------------------------------------------------
				# Blynk: Fix logging and move to RAMlog: https://github.com/MichaIng/DietPi/pull/2779
				if [[ -f '/etc/systemd/system/blynkserver.service' && -f '/mnt/dietpi_userdata/blynk/server.properties' ]]; then

					G_CONFIG_INJECT 'WorkingDirectory=' 'WorkingDirectory=/mnt/dietpi_userdata/blynk' /etc/systemd/system/blynkserver.service '\[Service\]'
					mkdir -p /var/log/blynk
					chown -R blynk:dietpi /var/log/blynk
					G_CONFIG_INJECT 'logs.folder=' 'logs.folder=/var/log/blynk' /mnt/dietpi_userdata/blynk/server.properties

				fi
				#-----------------------------------------------------------------------
				# PHP7.3 migration: https://github.com/MichaIng/DietPi/issues/2367
				# - Only upgrade versions lower than 7.2 and skip any check version Buster+ where this is impossible
				if (( $G_DISTRO < 5 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[89\]=2' /boot/dietpi/.installed && ! command -v php7.{2,3} > /dev/null; then

					echo 89 >> /var/tmp/dietpi/dietpi-update_reinstalls

					# Software which does not support PHP7.3, install PHP7.2 instead
					local PHP_NAME='php7.3'
					# - ownCloud up to v10.2
					if [[ -f '/var/www/owncloud/version.php' ]]; then

						# shellcheck disable=SC2016
						local oc_version_major=$(sed -n '/$OC_VersionString/{s/^[^0-9]*//;s/\..*$//;p;q}' /var/www/owncloud/version.php)
						# shellcheck disable=SC2016
						local oc_version_minor=$(sed -n '/$OC_VersionString/{s/^[^.]*\.//;s/\..*$//;p;q}' /var/www/owncloud/version.php)
						(( $oc_version_major < 10 || ( $oc_version_major == 10 && oc_version_minor < 3 ) )) && PHP_NAME='php7.2'

					fi

					G_WHIP_MSG "[ INFO ] PHP upgrade\n
Your PHP instance will be upgraded to ${PHP_NAME^^}. This enhances security and performance of your web applications and is required to run some of the latest web application versions, e.g. Nextcloud 17, ownCloud 10.3, phpBB 3.3 and others.\n
We will update webserver configurations and backup the whole /etc/php directory to /etc/php_bak, so you can recover custom settings.\n
NB: For any custom PHP-dependent web applications, which you have installed manually (outside of DietPi-Software), you might need to adjust the used socket to: /run/php/$PHP_NAME-fpm.sock
NBB: Reinstall manually installed PHP modules via: G_AGI $PHP_NAME-<mod_name>"

					# Backup config
					[[ -d '/etc/php' ]] && G_EXEC cp -a /etc/php{,_bak}

					# Update PHP socket
					# - Lighttpd
					[[ -f '/etc/lighttpd/conf-available/15-fastcgi-php.conf' ]] && sed -i "s@\"socket\".*\$@\"socket\" => \"/run/php/$PHP_NAME-fpm.sock\",@" /etc/lighttpd/conf-available/15-fastcgi-php.conf
					# - Nginx
					[[ -f '/etc/nginx/nginx.conf' ]] && sed -i "s#/run/php.*-fpm.sock#/run/php/$PHP_NAME-fpm.sock#g" /etc/nginx/nginx.conf

					# Mark old PHP packages for autoremoval
					local apackages=()
					mapfile -t apackages < <(dpkg --get-selections 'php7.[01]-*' 'libapache2-mod-php7.[01]' 2> /dev/null | mawk '{print $1}')
					apt-mark auto "${apackages[@]}" 2> /dev/null
					unset -v apackages

					# Disable old mod-php so that new version is enabled automatically on package install
					command -v a2dismod > /dev/null && a2dismod php7.{0,1} 2> /dev/null

				fi
				#-----------------------------------------------------------------------
				# Reinstalls
				#	Subsonic: https://github.com/MichaIng/DietPi/pull/2705
				[[ -L '/var/subsonic/transcode' ]] && rm /var/subsonic/transcode
				#	Plex Media Server: https://github.com/MichaIng/DietPi/pull/2722
				dpkg-query -s plexmediaserver-installer &> /dev/null && dpkg -r plexmediaserver-installer
				#	Logitech Media Server: https://github.com/MichaIng/DietPi/commit/eccef6700381c3f044ec4d435beb167736db0bb4
				if [[ -f '/etc/systemd/system/squeezeboxserver.service' ]]; then

					systemctl disable --now squeezeboxserver
					mv /etc/systemd/system/squeezeboxserver.service /etc/systemd/system/logitechmediaserver.service

				fi
				[[ -d '/etc/systemd/system/squeezeboxserver.service.d' ]] && mv /etc/systemd/system/squeezeboxserver.service.d /etc/systemd/system/logitechmediaserver.service.d
				#	SABnzbd: https://github.com/MichaIng/DietPi/pull/2768
				# v6.27	Jackett: https://github.com/MichaIng/DietPi/pull/2773
				if [[ -d '/opt/jackett/.config' ]]; then

					cp -a /opt/jackett/.config/. /opt/jackett/
					rm -R /opt/jackett/.config

				fi
				echo 34 35 42 47 48 114 139 >> /var/tmp/dietpi/dietpi-update_reinstalls

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 23 )); then

			#-------------------------------------------------------------------------------
			# Add Plex and Emby users to dietpi group to grant media and network mount access
			getent passwd emby &> /dev/null && usermod -aG dietpi emby
			getent passwd plex &> /dev/null && usermod -aG dietpi plex
			#-------------------------------------------------------------------------------
			# Patch Lighttpd config file on ARMv6 (Buster version installed): https://github.com/MichaIng/DietPi/issues/2808
			if [[ -f '/etc/lighttpd/lighttpd.conf' && ! -f '/usr/share/lighttpd/create-mime.assign.pl' && -f '/usr/share/lighttpd/create-mime.conf.pl' ]]; then

				sed -i 's|/usr/share/lighttpd/create-mime\.assign\.pl|/usr/share/lighttpd/create-mime.conf.pl|g' /etc/lighttpd/lighttpd.conf

			fi
			#-------------------------------------------------------------------------------
			# Restart DietPi-WiFi-Monitor to apply fixed script now: https://github.com/MichaIng/DietPi/issues/2802
			systemctl -q is-active dietpi-wifi-monitor && systemctl restart dietpi-wifi-monitor
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 24 )); then

			#-------------------------------------------------------------------------------
			# DietPi-Services 2.0
			rm -f /boot/dietpi/{,.}dietpi-process_tool
			if [[ -f '/usr/share/applications/dietpi-process_tool.desktop' ]]; then

				rm /usr/share/applications/dietpi-process_tool.desktop
				G_EXEC curl -sSfL https://github.com/$G_GITOWNER/DietPi/raw/$G_GITBRANCH/.conf/desktop/apps/dietpi-services.desktop -o /usr/share/applications/dietpi-services.desktop
				chmod +x /usr/share/applications/dietpi-services.desktop

			fi
			#-------------------------------------------------------------------------------
			# Disable APT cache by default (leaves package download dir at disk by default)
			if [[ ! -f '/etc/apt/apt.conf.d/99-dietpi-cache' ]]; then

				G_WHIP_MSG '[ INFO ] Disabling APT cache\n
We added new options to "dietpi-config" > "Advanced Options" > "APT Cache" to disable the APT cache or move cache, repo lists and/or package download dir to RAM.\n
By default we disable the APT cache, which saves 50 - 100 MiB disk writes on each "apt-get update" call, but slows down "apt-cache" calls.\n
Use "dietpi-config" to adjust these settings to your needs.'
				/boot/dietpi/func/dietpi-set_software apt-cache cache disable

			fi
			#-------------------------------------------------------------------------------
			# FFmpeg on RPi: Failsafe reinstall new APT package and mark priorly required libraries as auto + autoremove
			if (( $G_HW_MODEL < 10 )) && command -v ffmpeg > /dev/null; then

				[[ $(ffmpeg -version 2> /dev/null | sed -n '1{s/[^0-9]//g;p}') == 32* ]] && G_AGI --reinstall ffmpeg
				apt-mark auto libx264 libmp3lame libfdk-aac
				G_AGA

			fi
			#-------------------------------------------------------------------------------
			# Node-RED: Enable sudo permissions for all installs: https://github.com/MichaIng/DietPi/issues/2910
			getent passwd nodered &> /dev/null && echo 'nodered ALL=NOPASSWD: ALL' > /etc/sudoers.d/nodered
			#-------------------------------------------------------------------------------
			# DietPi-Survey now uses dietpi.txt for opt in/out state
			if [[ -f '/boot/dietpi/.dietpi-survey' ]]; then

				G_CONFIG_INJECT 'SURVEY_OPTED_IN=' "SURVEY_OPTED_IN=$(mawk 'NR==1' /boot/dietpi/.dietpi-survey)" /boot/dietpi.txt
				rm /boot/dietpi/.dietpi-survey

			fi
			#-------------------------------------------------------------------------------
			# Remove obsolete dietpi.txt entries
			# - https://github.com/MichaIng/DietPi/commit/b330594f0e63a40a75484647033c3b393ecd05b3#diff-aca2a37c06074a66f2588f7c9e84d07a
			sed -i '/AUTO_SETUP_NET_WIFI/{/AUTO_SETUP_NET_WIFI_ENABLED/!d}' /boot/dietpi.txt
			# - https://github.com/MichaIng/DietPi/commit/814823899667e896291ed240281cfd39971463d9#diff-aca2a37c06074a66f2588f7c9e84d07a
			sed -i '/CONFIG_SMBCLIENT/d' /boot/dietpi.txt
			sed -i '/CONFIG_CURLFTPFS/d' /boot/dietpi.txt
			sed -i '/CONFIG_NFSCLIENT/d' /boot/dietpi.txt
			#-------------------------------------------------------------------------------
			# Transmission: Fix web UI settings not being applied to settings file: https://github.com/MichaIng/DietPi/issues/2793
			[[ -f '/etc/systemd/system/transmission-daemon.service.d/dietpi-group.conf' ]] && echo -e '[Service]\nGroup=dietpi\nSupplementaryGroups=debian-transmission' > /etc/systemd/system/transmission-daemon.service.d/dietpi-group.conf
			#-------------------------------------------------------------------------------
			# RPi I-Sabre-Q2M: Switch systems to use the new integrated "i-sabre-q2m" overlay + remove obsolete "snd-bcm2835" module blacklisting (instead disable dtparam if blacklist found)
			[[ -f '/boot/config.txt' ]] && sed -i 's/i-sabre-k2m/i-sabre-q2m/g' /boot/config.txt
			if [[ -f '/etc/modprobe.d/rpi-bcm2708.conf' ]]; then

				G_CONFIG_INJECT 'dtparam=audio=' 'dtparam=audio=off' /boot/config.txt
				rm /etc/modprobe.d/rpi-bcm2708.conf

			fi
			#-------------------------------------------------------------------------------
			# x86_64: Cleanup config files to disable nouveau
			if (( $G_HW_ARCH == 10 )); then

				rm -f /etc/modprobe.d/*nouveau*
				cat << '_EOF_' > /etc/modprobe.d/dietpi-disable_nouveau.conf
blacklist nouveau
blacklist lbm-nouveau
options nouveau modeset=0
alias nouveau off
alias lbm-nouveau off
_EOF_
				# Update initramfs with above changes
				if command -v update-tirfs > /dev/null; then

					update-tirfs

				else

					update-initramfs -u

				fi

			fi
			#-------------------------------------------------------------------------------
			# RPi Buster: Re-apply firmware Buster-only repo, remove Stretch branch, reinstall raspi-copies-and-fills (on ARMv6/7 models) which is now compatible
			if (( $G_HW_MODEL < 10 && $G_DISTRO > 4 )); then

				echo 'deb https://archive.raspberrypi.org/debian/ buster main' > /etc/apt/sources.list.d/raspi.list
				G_AGUP
				(( $G_HW_ARCH == 3 )) || G_AGI raspi-copies-and-fills

			fi
			#-------------------------------------------------------------------------------
			# Install "haveged" entropy daemon by default on all non-RPi systems: https://github.com/MichaIng/DietPi/issues/2806
			(( $G_HW_MODEL > 9 )) && G_AGI haveged
			#-------------------------------------------------------------------------------
			# RPi3: Remove doubled config.txt temp_limit value due to: https://github.com/MichaIng/DietPi/commit/cafcbc599ef23c337e75003fb8eacc446877eaba#diff-68acf994541fd7b6ea4f6b02d04ee328L60
			if [[ $G_HW_MODEL == 3 ]] && (( $(grep -c '^[[:blank:]#]*temp_limit=' /boot/config.txt) > 1 )); then

				local current=$(grep '^[[:blank:]]*temp_limit=' /boot/config.txt | sed 's/^[^=]*=//' | tail -1) # Get current effective (last) value
				disable_error=1 G_CHECK_VALIDINT "$current" || current=75 # If none, use 75'c as DietPi default on RPi3
				sed -i '/^[[:blank:]#]*temp_limit=/d' /boot/config.txt # Remove all entries, including comments
				G_CONFIG_INJECT 'temp_limit=' "temp_limit=$current" /boot/config.txt # Re-add current effective value or default

			fi
			#-------------------------------------------------------------------------------
			# Reinstalls:
			#	O!MPD update to master: https://github.com/MichaIng/DietPi/pull/2884
			#	myMPD update to master: https://github.com/MichaIng/DietPi/pull/2883
			#	Gitea update to v1.8.X: https://github.com/MichaIng/DietPi/pull/2881
			# MPD: Remove obsolete and wrong RuntimeDirectory definition: https://github.com/MichaIng/DietPi/commit/882ddfb533fdc1fa597231824810909770a910c9
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				[[ -f '/lib/systemd/system/mpd.service' ]] && sed -i '/^[[:blank:]]*RuntimeDirectory=/d' /lib/systemd/system/mpd.service
				[[ -f '/var/www/ompd/include/config.inc.php' && ! -f '/var/www/ompd/include/config.local.inc.php' ]] && mv /var/www/ompd/include/config.inc.php /var/www/ompd/include/config.local.inc.php
				if grep -q '^aSOFTWARE_INSTALL_STATE\[148\]=2' /boot/dietpi/.installed; then

					G_WHIP_MSG '[ INFO ] myMPD will be updated to latest upstream version\n
Due to changes in how its configuration file "/etc/mympd/mympd.conf" is structured, we need to reset it.
A backup will be created to "/etc/mympd/mympd.conf.bak_DDMMYYY_N" from where you can recover custom settings.'
					G_BACKUP_FP /etc/mympd/mympd.conf
					[[ -f '/etc/mympd/mympd.conf' ]] && rm /etc/mympd/mympd.conf
					[[ -f '/etc/mympd/mympd.conf.dist' ]] && rm /etc/mympd/mympd.conf.dist
					# - Revert to systemd unit provided by installer
					[[ -f '/lib/systemd/system/mympd.service' ]] && rm /lib/systemd/system/mympd.service

				fi
				echo 129 148 165 >> /var/tmp/dietpi/dietpi-update_reinstalls

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 25 )); then

			#-------------------------------------------------------------------------------
			# Remove possible OpenMediaVault leftovers, that are not part of current OMV packages, thus save to remove: https://github.com/MichaIng/DietPi/issues/2994
			[[ -f '/etc/cron.d/openmediavault-rrdtoolgraph' ]] && rm /etc/cron.d/openmediavault-rrdtoolgraph
			[[ -f '/usr/sbin/omv-mkgraph' ]] && rm /usr/sbin/omv-mkgraph
			#-------------------------------------------------------------------------------
			# Disable pihole.log query logging: https://github.com/pi-hole/FTL/issues/614#issuecomment-510564476
			command -v pihole > /dev/null && pihole -l off
			#-------------------------------------------------------------------------------
			# Remove obsolete audio related services/scripts/settings: https://github.com/MichaIng/DietPi/pull/2988
			# RPi: Remove invalid I2C baudrate entries from config.txt. Do no apply any value to preserve current system state (default): https://github.com/MichaIng/DietPi/issues/2966
			# RPi: Remove obsolete camera module entry, which is loaded by default since kernel 4.19, instead add a blacklist entry if camera is disabled.
			# RPi: Further config.txt fixes: https://github.com/MichaIng/DietPi/pull/3000
			[[ -f '/var/lib/dietpi/postboot.d/sparky_unmute.sh' ]] && rm /var/lib/dietpi/postboot.d/sparky_unmute.sh
			[[ -f '/etc/systemd/system/rpi-bcm2835_forced_3.5mm.service' ]] && rm /etc/systemd/system/rpi-bcm2835_forced_3.5mm.service
			if (( $G_HW_MODEL < 10 )); then

				sed -i '/dtoverlay=i2s-mmap/d' /boot/config.txt
				sed -i '/dtoverlay=i2s=/d' /boot/config.txt
				sed -i '/dtoverlay=lirc-rpi/d' /boot/config.txt
				sed -i '/^[[:blank:]#]*dtparam=gpio_in_pin=25/d' /boot/config.txt
				sed -i '/^[[:blank:]#]*i2c_arm_baudrate=/d' /boot/config.txt
				sed -i '/^[[:blank:]#]*bcm2835-v4l2/d' /etc/modules
				grep -q '^[[:blank:]]*start_x=1' /boot/config.txt || /boot/dietpi/func/dietpi-set_hardware rpi-camera disable
				[[ -f '/etc/modprobe.d/disable_bt.conf' ]] && G_CONFIG_INJECT 'dtoverlay=disable-bt' 'dtoverlay=disable-bt' /boot/config.txt
				[[ -f '/etc/modprobe.d/disable_wifi_rpi3_onboard.conf' ]] && G_CONFIG_INJECT 'dtoverlay=disable-wifi' 'dtoverlay=disable-wifi' /boot/config.txt
				# Offer re-adding of "initial_turbo" on RPi: https://github.com/MichaIng/DietPi/issues/3147
				if ! grep -q '^[[:blank:]]*initial_turbo' /boot/config.txt; then

					sed -i '\|issues/1836|d' /boot/config.txt # Remove obsolete comment
					G_WHIP_BUTTON_OKAY_TEXT='Yes' G_WHIP_BUTTON_CANCEL_TEXT='No' G_WHIP_YESNO 'Re-adding "initial_turbo" option\n
The firmware issues with the "initial_turbo" option have been fixed a recent update: https://github.com/raspberrypi/firmware/issues/1005\n
This option allows you to force highest CPU frequency for a set amount of seconds during boot. This significantly reduces boot time on RPi since it by default boots with lowest frequencies, until a systemd unit sets the chosen CPU governor at later boot stage. You can now set this setting again via:
 - dietpi-config > Performance Options > ARM Initial Turbo\n
Do you want to have the recommended "initial_turbo=20" re-added to your config.txt now?' && G_CONFIG_INJECT 'initial_turbo=' 'initial_turbo=20' /boot/config.txt

				fi

			fi
			#-------------------------------------------------------------------------------
			# Docker: Remove obsolete RPi fix: https://github.com/MichaIng/DietPi/issues/2282 (new version is available now)
			[[ -f '/etc/apt/preferences.d/dietpi-docker_fix' ]] && rm /etc/apt/preferences.d/dietpi-docker_fix
			#-------------------------------------------------------------------------------
			# Config file renaming: https://github.com/MichaIng/DietPi/pull/3000
			[[ -f '/etc/modprobe.d/disable_bt.conf' ]] && mv /etc/modprobe.d/disable_bt.conf /etc/modprobe.d/dietpi-disable_bluetooth.conf
			[[ -f '/etc/modprobe.d/disable_wifi.conf' ]] && mv /etc/modprobe.d/disable_wifi.conf /etc/modprobe.d/dietpi-disable_wifi.conf
			[[ -f '/etc/modprobe.d/disable_wifi_rpi3_onboard.conf' ]] && rm /etc/modprobe.d/disable_wifi_rpi3_onboard.conf
			for i in '8192cu' '8188eu' '8189es' '8723bs' 'wlan_8192eu'
			do

				[[ -f /etc/modprobe.d/${i}.conf ]] || continue
				cat /etc/modprobe.d/${i}.conf >> /etc/modprobe.d/dietpi-disable_wifi_powersaving.conf
				rm /etc/modprobe.d/${i}.conf

			done
			#-------------------------------------------------------------------------------
			# Remove old scripts/files that have been removed from code source long time ago but never from updated systems
			rm -f /boot/dietpi/func/dietpi-set_{curlftpfs,nfsclient,smbclient}
			rm -f /boot/dietpi/.dietpi-backup_{include,exclude}
			[[ -f '/var/log/boottime' ]] && rm /var/log/boottime # https://github.com/MichaIng/DietPi/commit/e6713f874cac47ef11912e3455bf1abe58bfd412
			#-------------------------------------------------------------------------------
			# Move DietPi-NordVPN service to /etc/systemd/system: https://github.com/MichaIng/DietPi/pull/3084
			[[ -f '/lib/systemd/system/dietpi-nordvpn.service' ]] && mv /lib/systemd/system/dietpi-nordvpn.service /etc/systemd/system/dietpi-nordvpn.service
			#-------------------------------------------------------------------------------
			# RPi
			# - Replace haveged with rng-tools5, which is proven to work on RPi, is default on Raspbian and uses less RAM on idle
			# - Fix headless mode
			# - Remove obsolete Kodi repo for Beta testers + replace obsolete kodi-rpi4 package with new official Kodi from RPi repository
			# - On RPi4 raise temp_limit from 65°C tp 75°C as new default value: https://github.com/MichaIng/DietPi/issues/3151
			if (( $G_HW_MODEL < 10 )); then

				systemctl disable --now haveged 2> /dev/null
				G_AGP haveged
				G_AGI rng-tools5
				if grep -q '^[[:blank:]]*hdmi_ignore_hotplug=1' /boot/config.txt && grep -q '^[[:blank:]]*hdmi_ignore_composite=1' /boot/config.txt; then

					/boot/dietpi/func/dietpi-set_hardware headless enable
					tvservice -o

				fi
				sed -i '/hdmi_ignore_composite/d' /boot/config.txt
				rm -f /etc/apt/sources.list.d/{dietpi-kodi,pipplware,kodi}.list
				if dpkg-query -s kodi-rpi4 &> /dev/null; then

					G_DIETPI-NOTIFY 2 'Replacing obsolete kodi-rpi4 package with new official Kodi from RPi repository...'
					G_AGP kodi-rpi4
					mkdir -p /etc/polkit-1/localauthority/50-local.d # https://github.com/MichaIng/DietPi/issues/3031#issuecomment-540477241
					G_AGI kodi

				fi
				(( $G_HW_MODEL == 4 )) && grep -q '^[[:blank:]]*temp_limit=65' /boot/config.txt && G_CONFIG_INJECT 'temp_limit=' 'temp_limit=75' /boot/config.txt

			fi
			#-------------------------------------------------------------------------------
			# Run "setupcon --save" to force font and cached console+keyboard script renewal. This solves an issue on Buster, where the "console-setup" service fails to do this on boot in cases: https://github.com/MichaIng/DietPi/issues/2912#issuecomment-532100542
			command -v setupcon > /dev/null && setupcon --save
			#-------------------------------------------------------------------------------
			# Failsafe, assure /var/tmp 1777 permissions: https://github.com/MichaIng/DietPi/issues/1144#issuecomment-517338321
			chmod 1777 /var/tmp
			#-------------------------------------------------------------------------------
			# Reinstalls and software install changes
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				# Remove obsolete install states: TightVPN and SDL2
				sed -Ei '/^aSOFTWARE_INSTALL_STATE\[(27|140)\]=/d' /boot/dietpi/.installed

				# Gogs: Remove /etc/__MACOSX that comes from our archive on ARMv6
				if grep -q '^aSOFTWARE_INSTALL_STATE\[49\]=2' /boot/dietpi/.installed; then

					[[ $G_HW_ARCH == 1 && -d '/etc/__MACOSX' ]] && rm -R /etc/__MACOSX

				fi
				# Pi-hole: Update blocking page implementation and webserver configs: https://github.com/MichaIng/DietPi/pull/3072
				if [[ -f '/etc/pihole/pihole-FTL.conf' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[93\]=2' /boot/dietpi/.installed; then

					[[ -L '/var/www/index.php' && $(readlink -f '/var/www/index.php') == '/var/www/html/pihole/index.php' ]] && rm /var/www/index.php
					if command -v a2ensite > /dev/null && grep -q '^aSOFTWARE_INSTALL_STATE\[83\]=2' /boot/dietpi/.installed; then

						G_EXEC curl -sSfL "https://raw.githubusercontent.com/$G_GITOWNER/DietPi/$G_GITBRANCH/.conf/dps_93/apache.block_public_admin.conf" -o /etc/apache2/sites-available/dietpi-pihole-block_public_admin.conf
						G_EXEC curl -sSfL "https://raw.githubusercontent.com/$G_GITOWNER/DietPi/$G_GITBRANCH/.conf/dps_93/apache.pihole.conf" -o /etc/apache2/sites-available/dietpi-pihole.conf
						a2ensite dietpi-pihole
						if grep -q 'BLOCKINGMODE=IP-NODATA-AAAA' /etc/pihole/pihole-FTL.conf; then

							[[ -f '/var/www/index.html' ]] && mv /var/www/index.html /var/www/index.html.bak
							G_CONFIG_INJECT 'ErrorDocument 404' 'ErrorDocument 404 /html/pihole/index.php' /etc/apache2/sites-available/dietpi-pihole.conf

						fi

					fi
					if command -v lighttpd-enable-mod > /dev/null && grep -q '^aSOFTWARE_INSTALL_STATE\[84\]=2' /boot/dietpi/.installed; then

						G_EXEC curl -sSfL "https://raw.githubusercontent.com/$G_GITOWNER/DietPi/$G_GITBRANCH/.conf/dps_93/lighttpd.block_public_admin.conf" -o /etc/lighttpd/conf-available/99-dietpi-pihole-block_public_admin.conf
						G_EXEC curl -sSfL "https://raw.githubusercontent.com/$G_GITOWNER/DietPi/$G_GITBRANCH/.conf/dps_93/lighttpd.pihole.conf" -o /etc/lighttpd/conf-available/99-dietpi-pihole.conf
						lighttpd-enable-mod dietpi-pihole
						if grep -q 'BLOCKINGMODE=IP-NODATA-AAAA' /etc/pihole/pihole-FTL.conf; then

							[[ -f '/var/www/index.lighttpd.html' ]] && mv /var/www/index.lighttpd.html /var/www/index.lighttpd.html.bak
							G_CONFIG_INJECT 'server.error-handler-404' 'server.error-handler-404 = "/html/pihole/index.php"' /etc/lighttpd/conf-available/99-dietpi-pihole.conf

						fi

					fi
					if [[ -d '/etc/nginx/sites-dietpi' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[85\]=2' /boot/dietpi/.installed; then

						# Update Nginx default vhost, which is required to assure access restrictions for Pi-hole
						G_BACKUP_FP /etc/nginx/sites-available/default
						G_EXEC curl -sSfL "https://raw.githubusercontent.com/$G_GITOWNER/DietPi/$G_GITBRANCH/.conf/dps_85/nginx.default" -o /etc/nginx/sites-available/default
						G_EXEC curl -sSfL "https://raw.githubusercontent.com/$G_GITOWNER/DietPi/$G_GITBRANCH/.conf/dps_93/nginx.block_public_admin.conf" -o /etc/nginx/sites-dietpi/dietpi-pihole-block_public_admin.off
						G_EXEC curl -sSfL "https://raw.githubusercontent.com/$G_GITOWNER/DietPi/$G_GITBRANCH/.conf/dps_93/nginx.pihole.conf" -o /etc/nginx/sites-dietpi/dietpi-pihole.conf
						if grep -q 'BLOCKINGMODE=IP-NODATA-AAAA' /etc/pihole/pihole-FTL.conf; then

							[[ -f '/var/www/index.html' ]] && mv /var/www/index.html /var/www/index.html.bak
							G_CONFIG_INJECT 'error_page 404' 'error_page 404 /html/pihole/index.php;' /etc/nginx/sites-dietpi/dietpi-pihole.conf

						fi

					fi
					systemctl is-enabled dhcpcd &> /dev/null && ! pgrep dhcpcd &> /dev/null && systemctl disable dhcpcd

				fi
				# X11: Fix drivers and config on Odroid C2: https://github.com/MichaIng/DietPi/issues/3028
				if (( $G_HW_MODEL == 12 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[6\]=2' /boot/dietpi/.installed; then

					G_BACKUP_FP /etc/X11/xorg.conf
					G_EXEC curl -sSfL "https://raw.githubusercontent.com/$G_GITOWNER/DietPi/$G_GITBRANCH/.conf/dps_6/xorg_c2.conf" -o /etc/X11/xorg.conf
					apt-mark auto xf86-video-mali-odroid
					# Kodi: Remove PulseAudio, not required by Kodi anymore, but ask user first
					if grep -q '^aSOFTWARE_INSTALL_STATE\[31\]=2' /boot/dietpi/.installed; then

						G_WHIP_YESNO 'PulseAudio was installed together with Kodi, but it is not required anymore. If you did not install it manually for a special purpose, it is safe to remove it.\n
Do you want to keep PulseAudio installed?' || apt-mark auto pulseaudio

					fi
					G_AGA
					G_AGI --reinstall aml-libs-odroid mali450-odroid libump-odroid xf86-video-fbturbo-odroid

				fi
				# myMPD: https://github.com/MichaIng/DietPi/pull/3110
				if grep -q '^aSOFTWARE_INSTALL_STATE\[148\]=2' /boot/dietpi/.installed; then

					# NB: On Debian Buster by default /lib is a symlink to /usr/lib, thus the below fails as both files are the same. However it does not hurt and assures no obsolete service file will be left (after uninstall).
					[[ -f '/usr/lib/systemd/system/mympd.service' ]] && mv /usr/lib/systemd/system/mympd.service /lib/systemd/system/mympd.service 2> /dev/null
					[[ -f '/etc/systemd/systemd/mympd.service.d/dietpi-group.conf' ]] && rm /etc/systemd/systemd/mympd.service.d/dietpi-group.conf
					[[ -d '/etc/systemd/systemd/mympd.service.d' ]] && rmdir --ignore-fail-on-non-empty /etc/systemd/systemd/mympd.service.d

				fi
				# Fail2Ban: Enable service since it is not controlled by DietPi-Services anymore: https://github.com/MichaIng/DietPi/commit/4d6ccbeee47b54247613f880a03339ff8a72f24d
				grep -q '^aSOFTWARE_INSTALL_STATE\[73\]=2' /boot/dietpi/.installed && systemctl enable --now fail2ban
				# Certbot: https://github.com/MichaIng/DietPi/issues/3111
				if grep -q '^aSOFTWARE_INSTALL_STATE\[92\]=2' /boot/dietpi/.installed; then

					# Apache
					if grep -q '^aSOFTWARE_INSTALL_STATE\[83\]=2' /boot/dietpi/.installed; then

						G_AGI python3-certbot-apache
						grep -q '^[[:blank:]]*authenticator[[:blank:]]*=[[:blank:]]*webroot' /etc/letsencrypt/renewal/*.conf 2> /dev/null &&
						G_WHIP_YESNO '[Certbot] Switch back to native Apache authentication method\n
Your Certbot authenticates with the "webroot" method, while you have an Apache webserver installed. This was required some time ago due to a sudden change by Let'\''s Encrypt, which made the Apache authentication method fail.
Meanwhile, with current Certbot version, this bug has been fixed and we got some reports where the webroot method does not work reliable instead, leaving you with an expired HTTPS certificate in cases.\n
Would you like to switch back to the Apache authentication method now?' && certbot renew --force-renewal -a apache

					# Nginx
					elif grep -q '^aSOFTWARE_INSTALL_STATE\[85\]=2' /boot/dietpi/.installed; then

						G_AGI python3-certbot-nginx
						grep -q '^[[:blank:]]*authenticator[[:blank:]]*=[[:blank:]]*webroot' /etc/letsencrypt/renewal/*.conf 2> /dev/null &&
						G_WHIP_YESNO '[Certbot] Switch back to native Nginx authentication method\n
Your Certbot authenticates with the "webroot" method, while you have an Nginx webserver installed. This was required some time ago due to a sudden change by Let'\''s Encrypt, which made the Nginx authentication method fail.
Meanwhile, with current Certbot version, this bug has been fixed and we got some reports where the webroot method does not work reliable instead, leaving you with an expired HTTPS certificate in cases.\n
Would you like to switch back to the Nginx authentication method now?' && certbot renew --force-renewal -a nginx

					fi

				fi
				# Mono: Use new Buster repo on Buster/Bullseye systems
				(( $G_DISTRO > 4 )) && [[ -f '/etc/apt/sources.list.d/mono-xamarin.list' ]] && sed -i 's/stretch/buster/g' /etc/apt/sources.list.d/mono-xamarin.list
				# Aria2: https://github.com/MichaIng/DietPi/pull/3139
				if [[ -f '/var/lib/dietpi/dietpi-software/installed/aria2.conf' ]]; then

					# If aria2.conf exists on new location, it must have been installed with new code already, thus old file is obsolete.
					if [[ -f '/mnt/dietpi_userdata/aria2/aria2.conf' ]]; then

						G_EXEC rm /var/lib/dietpi/dietpi-software/installed/aria2.conf

					else

						# Apply session save/resume feature but do not overwrite existing settings
						GCI_PRESERVE=1 G_CONFIG_INJECT 'input-file=' 'input-file=/mnt/dietpi_userdata/downloads/aria2.session' /var/lib/dietpi/dietpi-software/installed/aria2.conf
						local fp_input=$(sed -n '/^[[:blank:]]*input-file=/{s/^[^=]*=//p;q}' /var/lib/dietpi/dietpi-software/installed/aria2.conf)
						GCI_PRESERVE=1 G_CONFIG_INJECT 'save-session=' "save-session=$fp_input" /var/lib/dietpi/dietpi-software/installed/aria2.conf
						GCI_PRESERVE=1 G_CONFIG_INJECT 'save-session-interval=' 'save-session-interval=60' /var/lib/dietpi/dietpi-software/installed/aria2.conf
						# Move aria2.conf to new location
						G_EXEC mkdir -p /mnt/dietpi_userdata/aria2
						G_EXEC mv /var/lib/dietpi/dietpi-software/installed/aria2.conf /mnt/dietpi_userdata/aria2/

					fi

				fi
				# Webmin: https://github.com/MichaIng/DietPi/commit/ec55d49a488fd9cb1dbb18cbfa067b5d1d1a974e
				echo 115 132 >> /var/tmp/dietpi/dietpi-update_reinstalls

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 26 )); then

			#-------------------------------------------------------------------------------
			# ownCloud: Remove obsolete PHP7.3 block: https://github.com/MichaIng/DietPi/pull/3169
			[[ -f '/etc/apt/preferences.d/dietpi-owncloud' ]] && rm /etc/apt/preferences.d/dietpi-owncloud
			#-------------------------------------------------------------------------------
			# RPi4 EEPROM install/update: https://github.com/MichaIng/DietPi/issues/3217
			(( $G_HW_MODEL == 4 )) && /boot/dietpi/func/dietpi-set_hardware rpi-eeprom
			#-------------------------------------------------------------------------------
			# Remove obsolete apt-transport-https on Buster+ where it is a transitional dummy package only, HTTPS support fixed part of apt: https://packages.debian.org/buster/apt-transport-https
			(( $G_DISTRO > 4 )) && G_AGP apt-transport-https
			#-------------------------------------------------------------------------------
			# Remove microcode packages from VM, where they are and must be without effect
			(( $G_HW_MODEL == 20 )) && G_AGP {intel,amd64}-microcode && G_AGA
			#-------------------------------------------------------------------------------
			G_DIETPI-NOTIFY 2 'Removing obsolete DietPi files that could have remained on older systems...'
			rm -Rfv /boot/dietpi/{server_version*,login}
			#-------------------------------------------------------------------------------
			# Mask ARMbian services, which are otherwise re-enabled on related APT package upgrade
			local apackages=()
			mapfile -t apackages < <(dpkg --get-selections 'linux-*-root-*' 2> /dev/null | mawk '{print $1}')
			[[ ${apackages[0]} ]] && G_DIETPI-NOTIFY 2 'Masking and removing conflicting ARMbian services and files...'
			for i in "${apackages[@]}"
			do

				local aservices=()
				mapfile -t aservices < <(dpkg -L "$i" | sed -n 's|^/lib/systemd/system/\([^/]*\)\.service$|\1|p')
				[[ ${aservices[*]} == *'armbian'* ]] || continue # Failsafe
				systemctl disable --now "${aservices[@]}" 2> /dev/null
				systemctl mask "${aservices[@]}" 2> /dev/null

			done
			unset -v aservices
			rm -vf /lib/systemd/system/*armbian*
			rm -vf /etc/apt/apt.conf.d/*armbian*
			rm -vf /etc/cron.*/*armbian*
			#rm -vf /etc/default/*armbian* # Required for ARMbian root package upgrade
			rm -vf /etc/update-motd.d/*armbian*
			rm -vf /etc/profile.d/*armbian*
			#[[ -d '/usr/lib/armbian' ]] && rm -vR /usr/lib/armbian # Required for ARMbian root package upgrade
			#[[ -d '/usr/share/armbian' ]] && rm -vR /usr/share/armbian # Required for ARMbian root package upgrade
			# Place DPKG exclude file, especially to skip cron jobs, which are doomed to fail and an unnecessary overhead + syslog spam on DietPi
			[[ -f '/etc/armbian-release' ]] && cat << '_EOF_' > /etc/dpkg/dpkg.cfg.d/dietpi-no_armbian
# Exclude conflicting ARMbian files
path-exclude /lib/systemd/system/*armbian*
path-exclude /etc/apt/apt.conf.d/*armbian*
path-exclude /etc/cron.*/*armbian*
#path-exclude /etc/default/*armbian* # Required for ARMbian root package upgrade
path-exclude /etc/update-motd.d/*armbian*
path-exclude /etc/profile.d/*armbian*
#path-exclude /usr/lib/armbian # Required for ARMbian root package upgrade
#path-exclude /usr/share/armbian # Required for ARMbian root package upgrade
_EOF_
			# Unhold ARMbian packages (set on hold via DietPi-PREP until v6.27)
			mapfile -t apackages < <(dpkg --get-selections linux-{dtb,u,image,"$G_DISTRO_NAME"}-* sunxi-tools 2> /dev/null | mawk '{print $1}')
			[[ ${apackages[0]} && -f '/etc/armbian-release' ]] && apt-mark unhold "${apackages[@]}" 2> /dev/null
			unset -v apackages
			#-------------------------------------------------------------------------------
			# Reinstalls
			#	Syncthing: https://github.com/MichaIng/DietPi/pull/3202
			#	Grafana: https://github.com/MichaIng/DietPi/issues/3213
			#	Jackett: https://github.com/MichaIng/DietPi/issues/2593
			# v6.33	Amiberry: https://github.com/MichaIng/DietPi/pull/3252
			#	Home Assistant: No reinstall but inform user about required Python update: https://github.com/MichaIng/DietPi/pull/3220
			# v6.29	Allo web UI: https://github.com/MichaIng/DietPi/pull/3282
			#	GMediaRender: https://github.com/MichaIng/DietPi/issues/3263, https://github.com/MichaIng/DietPi/issues/3246
			#	phpMyAdmin: https://github.com/MichaIng/DietPi/issues/3284
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				if [[ -d '/home/homeassistant/.pyenv/versions/3.6.3' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[157\]=2' /boot/dietpi/.installed; then

					G_WHIP_MSG '[WARNING] Home Assistant: Python3.6 will be deprecated
\nThe Python version for your Home Assistant pyenv needs to be updated to avoid deprecation with new HA versions: https://github.com/MichaIng/DietPi/issues/3219
\nSince this can take a very long time, we do not automate this during the DietPi update. When you can effort the time, please run:
- dietpi-software reinstall 157'

				fi
				if [[ -d '/etc/syncthing' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[50\]=2' /boot/dietpi/.installed; then

					if [[ -d '/opt/syncthing' ]]; then

						G_EXEC cp -a /etc/syncthing/. /opt/syncthing/
						rm -R /etc/syncthing

					else

						G_EXEC mv /etc/syncthing /opt/syncthing

					fi
					[[ -d '/var/log/syncthing' ]] && rm -R /var/log/syncthing
					G_WHIP_MSG '[ INFO ] Syncthing reinstall
\nThe Syncthing binary has been moved from /etc/syncthing to /opt/syncthing.
\nThe service has been updated to support auto-updates. You may want to enable it via web UI.
\nFile logging has been disabled. To view Syncthing logs, run:
 - journalctl -u syncthing'

				fi
				if [[ $G_HW_ARCH == 1 && -f '/etc/apt/sources.list.d/grafana.list' ]] && grep -q 'bintray.com' /etc/apt/sources.list.d/grafana.list && grep -q '^aSOFTWARE_INSTALL_STATE\[77\]=2' /boot/dietpi/.installed; then

					G_DIETPI-NOTIFY 2 'Removing obsolete bintray.com APT repo prior to Grafana update...'
					rm -v /etc/apt/sources.list.d/grafana.list

				fi
				if [[ -f '/usr/local/lib/libSDL2.txt' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[108\]=2' /boot/dietpi/.installed; then

					G_DIETPI-NOTIFY 2 'Removing obsolete SDL2 libraries prior to Amiberry update...'
					rm -v /usr/local/lib/libSDL2*

				fi
				grep -q '^aSOFTWARE_INSTALL_STATE\[163\]=2' /boot/dietpi/.installed && G_AGP gmrender gmediarender
				grep -q '^aSOFTWARE_INSTALL_STATE\[90\]=2' /boot/dietpi/.installed && { G_AGP phpmyadmin; G_AGA; }
				echo 50 77 90 147 163 >> /var/tmp/dietpi/dietpi-update_reinstalls

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 28 )); then

			#-------------------------------------------------------------------------------
			# ZeroPi: Apply new revision code
			if [[ -f '/etc/armbian-release' ]] && grep -q '^BOARD=zeropi' /etc/armbian-release; then

				echo 59 > /etc/.dietpi_hw_model_identifier
				/boot/dietpi/func/dietpi-obtain_hw_model

			fi
			#-------------------------------------------------------------------------------
			G_DIETPI-NOTIFY 2 'Re-allowing PHP7.3 when phpBB is installed, supported since v3.3.0'
			[[ -f '/etc/apt/preferences.d/dietpi-phpbb' ]] && rm -v /etc/apt/preferences.d/dietpi-phpbb
			#-------------------------------------------------------------------------------
			# Remove Armbian-related dpkg config on non-Armbian devices
			[[ -f '/etc/dpkg/dpkg.cfg.d/dietpi-no_armbian' && ! -f '/etc/armbian-release' ]] && rm -v /etc/dpkg/dpkg.cfg.d/dietpi-no_armbian
			#-------------------------------------------------------------------------------
			# Remove Armbian zRAM logrotate.service override and exclude via dpkg.cfg
			if [[ -f '/etc/dpkg/dpkg.cfg.d/dietpi-no_armbian' ]]; then

				[[ -L '/etc/systemd/system/logrotate.service' ]] || rm -fv /etc/systemd/system/logrotate.service
				grep -q 'logrotate\.service' /etc/dpkg/dpkg.cfg.d/dietpi-no_armbian || echo 'path-exclude /etc/systemd/system/logrotate.service' >> /etc/dpkg/dpkg.cfg.d/dietpi-no_armbian

			fi
			#-------------------------------------------------------------------------------
			# Translate old DietPi-LED_control settings into new udev rules, remove old config and script location: https://github.com/MichaIng/DietPi/pull/3397
			if [[ -f '/boot/dietpi/.dietpi-led_control' ]]; then

				G_DIETPI-NOTIFY 2 'Translating old DietPi-LED_control settings into new udev rules'
				local led trigger
				while read -r led trigger
				do

					>> /etc/udev/rules.d/dietpi-led_control.rules
					G_CONFIG_INJECT "SUBSYSTEM==\"leds\", KERNEL==\"$led\"" "SUBSYSTEM==\"leds\", KERNEL==\"$led\", ACTION==\"add\", ATTR{trigger}=\"$trigger\"" /etc/udev/rules.d/dietpi-led_control.rules

				done < /boot/dietpi/.dietpi-led_control

			fi
			G_DIETPI-NOTIFY 2 'Removing old DietPi-LED_control config and script location'
			rm -fv /boot/dietpi/{.,func/}dietpi-led_control
			#-------------------------------------------------------------------------------
			G_DIETPI-NOTIFY 2 'Installing vmtouch as replacement for DietPi-RAMdisk' # https://github.com/MichaIng/DietPi/issues/3288
			G_EXEC curl -sSfLO "https://dietpi.com/downloads/binaries/$G_DISTRO_NAME/vmtouch_$G_HW_ARCH_NAME.deb"
			G_AGI "./vmtouch_$G_HW_ARCH_NAME.deb"
			rm "vmtouch_$G_HW_ARCH_NAME.deb"
			#-------------------------------------------------------------------------------
			G_DIETPI-NOTIFY 2 'Removing obsolete flag files'
			rm -fv /boot/dietpi/.{update_available,timesync_exit_status,network} /var/lib/dietpi/.ntpd_override /tmp/.dietpi_motd
			#-------------------------------------------------------------------------------
			[[ -f '/boot/dietpi/.dietpi-backup_settings' ]] && l_message='Adjusting changed DietPi-Backup variable name' G_EXEC sed -i 's/^FP_TARGET_BACKUP=/FP_TARGET=/' /boot/dietpi/.dietpi-backup_settings
			#-------------------------------------------------------------------------------
			if [[ -f '/etc/default/crda' ]]; then

				G_DIETPI-NOTIFY 2 'Migrating WiFi country code to be applied via native crda facility'
				local country_code=$(iw reg get | mawk '/country/{print $2;exit}' | tr -d ':')
				G_CONFIG_INJECT 'REGDOMAIN=' "REGDOMAIN=$country_code" /etc/default/crda
				G_CONFIG_INJECT 'AUTO_SETUP_NET_WIFI_COUNTRY_CODE=' "AUTO_SETUP_NET_WIFI_COUNTRY_CODE=$country_code" /boot/dietpi.txt
				# Remove from wpa_supplicant.conf
				[[ -f '/etc/wpa_supplicant/wpa_supplicant.conf' ]] && sed -i '/^[[:blank:]]*country=/d' /etc/wpa_supplicant/wpa_supplicant.conf

			fi
			#-------------------------------------------------------------------------------
			G_DIETPI-NOTIFY 2 'Removing obsolete dietpi.txt entries'
			sed -i '/CONFIG_AUTO_DIETPI_UPDATES=/d' /boot/dietpi.txt
			sed -i '/CONFIG_WIFI_COUNTRY_CODE=/d' /boot/dietpi.txt
			#-------------------------------------------------------------------------------
			G_DIETPI-NOTIFY 2 'Removing obsolete dietpi-software config directory'
			[[ -d '/var/lib/dietpi/dietpi-software/conf' ]] && rm -Rv /var/lib/dietpi/dietpi-software/conf
			#-------------------------------------------------------------------------------
			G_DIETPI-NOTIFY 2 'Removing obsolete hint about /DietPi RAMdisk from /boot config files'
			[[ -f '/boot/dietpi.txt' ]] && sed -Ei '/^# - (Modifications to \/boot\/dietpi\.txt|Please ensure you edit from the DietPi-RAMdisk)/d' /boot/dietpi.txt
			[[ -f '/boot/config.txt' ]] && sed -Ei '/^# - (Modifications to \/boot\/config\.txt|Please ensure you edit from the DietPi-RAMdisk)/d' /boot/config.txt
			[[ -f '/boot/boot.ini' ]] && sed -Ei '/^# - (Modifications to \/boot\/boot\.ini|Please ensure you edit from the DietPi-RAMdisk)/d' /boot/boot.ini
			#-------------------------------------------------------------------------------
			# Sparky SBC: Update kernel/drivers
			if (( $G_HW_MODEL == 70 )); then

				G_DIETPI-NOTIFY 2 'Update Sparky SBC kernel, drivers and services...'

				# Install latest kernel/drivers
				G_EXEC curl -sSfL https://raw.githubusercontent.com/sparky-sbc/sparky-test/master/dragon_fly_check/uImage -o /boot/uImage
				G_EXEC curl -sSfLO https://raw.githubusercontent.com/sparky-sbc/sparky-test/master/dragon_fly_check/3.10.38.bz2
				G_EXEC tar -xf 3.10.38.bz2 -C /lib/modules/
				rm -v 3.10.38.bz2
				# - USB audio update
				G_EXEC curl -sSfL https://raw.githubusercontent.com/sparky-sbc/sparky-test/master/dsd-marantz/snd-usb-audio.ko -o /lib/modules/3.10.38/kernel/sound/usb/snd-usb-audio.ko
				# - Remove obsolete WiFi driver files
				rm -Rfv /lib/modules/3.10.38/kernel/drivers/net/wireless/rtl8812au /etc/modprobe.d/wlan_8812au.conf
				[[ -f '/etc/modprobe.d/dietpi-disable_wifi_powersaving.conf' ]] && G_CONFIG_INJECT 'options wlan_8812au rtw_power_mgnt=0' 'options wlan_8812au rtw_power_mgnt=0' /etc/modprobe.d/dietpi-disable_wifi_powersaving.conf
				# Rename modprobe configs
				[[ -f '/etc/modprobe.d/disable_sparkysbc_gpu.conf' ]] && mv /etc/modprobe.d/{,dietpi-}disable_sparkysbc_gpu.conf
				[[ -f '/etc/modprobe.d/disable_sparkysbc_touchscreen.conf' ]] && mv /etc/modprobe.d/{,dietpi-}disable_sparkysbc_touchscreen.conf

			#-------------------------------------------------------------------------------
			# Sparky SBC: Update Ethernet script

				if [[ -f '/etc/systemd/system/sparky_eth_controller.service' ]]; then

					systemctl disable sparky_eth_controller
					rm -fv /etc/systemd/system/sparky_eth_controller.service*

				fi
				[[ -f '/usr/local/bin/sparky_eth_controller.sh' ]] && rm -v /usr/local/bin/sparky_eth_controller.sh
				cat << '_EOF_' > /var/lib/dietpi/services/dietpi-sparkysbc_ethernet.sh
#!/bin/dash
# Called from: /etc/systemd/system/dietpi-sparkysbc_ethernet.service
# We need to wait until USB Ethernet is established on USB bus, which takes much longer than onboard init.
sleep 20
# Disable onboard Ethernet if USB Ethernet is found
if ip a s eth1 > /dev/null 2>&1; then

	echo 'blacklist ethernet' > /etc/modprobe.d/dietpi-disable_sparkysbc_ethernet.conf
	reboot

# Enable onboard Ethernet if no adapter is found
elif ! ip a s eth0 > /dev/null 2>&1; then

	rm -f /etc/modprobe.d/dietpi-disable_sparkysbc_ethernet.conf
	reboot

fi
_EOF_
				G_EXEC chmod +x /var/lib/dietpi/services/dietpi-sparkysbc_ethernet.sh
				cat << '_EOF_' > /etc/systemd/system/dietpi-sparkysbc_ethernet.service
[Unit]
Description=Sparky SBC auto detect and toggle onboard/USB Ethernet
Wants=network-online.target
After=network-online.target

[Service]
RemainAfterExit=yes
ExecStart=/var/lib/dietpi/services/dietpi-sparkysbc_ethernet.sh

[Install]
WantedBy=multi-user.target
_EOF_
				systemctl enable dietpi-sparkysbc_ethernet
				[[ -f '/etc/modprobe.d/disable_sparkysbc_ethernet.conf' ]] && mv /etc/modprobe.d/{,dietpi-}disable_sparkysbc_ethernet.conf

			fi
			#-------------------------------------------------------------------------------
			# Fix /var/lib/dietpi permissions: https://github.com/MichaIng/DietPi/issues/3322
			local dirs=()
			mapfile -t dirs < <(find /var/lib/dietpi -type d)
			chmod -f +x "${dirs[@]}" /var/lib/dietpi/services/*sh /var/lib/dietpi/dietpi-software/installed/*sh
			unset -v dirs
			#-------------------------------------------------------------------------------
			# Installed software changes
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				# Sonarr/Radarr/Lidarr: Inform user about permission changes: https://github.com/MichaIng/DietPi/pull/3349
				if grep -qE '^aSOFTWARE_INSTALL_STATE\[(106|144|145)\]=2' /boot/dietpi/.installed; then

					G_WHIP_MSG '[ INFO ] Sonarr/Radarr/Lidarr permission changes
\nThe service permissions for Sonarr/Radarr/Lidarr will become stricter with new installs and reinstalls. They will only be able to read/write files to locations inside /mnt/.
\nWe do not force a reinstall, hence you do not need to take action for now. However, the reinstall enables some other enhancements, e.g. it will allow you to update these programs through their internal web UI updater without issues.
To reinstall now, run: "dietpi-software reinstall 106 144 145"
\nIf you added custom download/media directories outside of /mnt/, after reinstall, please do the following:
1. Run "dietpi-services" from console
2. Select "sonarr", "radarr" and/or "lidarr" respectively
3. Select "Edit"
4. Uncomment (remove leading "#") the line, starting with "ReadWritePaths="
5. Add your custom path to the end of this line, separated by one space
6. Press ctrl+o buttons to save and ctrl+x to exit'

				fi
				# Update .network info file locations in existing software services
				[[ -f '/etc/wireguard/wg0.conf' ]] && sed -Ei 's@/(DietPi|boot)/dietpi/\.network@/run/dietpi/.network@g' /etc/wireguard/wg0.conf
				[[ -f '/etc/systemd/system/gmrender.service' ]] && sed -Ei 's@/(DietPi|boot)/dietpi/\.network@/run/dietpi/.network@g' /etc/systemd/system/gmrender.service
				# Pi-hole: Assure v5 compatibility
				if getent group pihole > /dev/null && command -v php > /dev/null; then

					G_DIETPI-NOTIFY 2 'Assuring Pi-hole v5 compatibility...'
					usermod -aG pihole www-data
					if command -v php7.3 > /dev/null; then

						G_AGI php7.3-intl

					elif command -v php7.2 > /dev/null; then

						G_AGI php7.2-intl

					elif command -v php7.4 > /dev/null; then

						G_AGI php7.4-intl

					fi

				fi
				# Reinstalls
				#	HAProxy: https://github.com/MichaIng/DietPi/pull/3416
				if [[ -f '/etc/init.d/haproxy' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[98\]=2' /boot/dietpi/.installed; then

					G_DIETPI-NOTIFY 2 'Preparing HAProxy update, removing obsolete sysvinit service...'
					systemctl unmask haproxy
					rm -v /etc/init.d/haproxy
					update-rc.d -f haproxy remove

				fi
				# v6.33	Amiberry: https://github.com/MichaIng/DietPi/issues/3357#issuecomment-593868445
				#	Allo web UI: Updated to v13.2 to match DietPi v6.29 API
				echo 98 160 >> /var/tmp/dietpi/dietpi-update_reinstalls

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 29 )); then

			#-------------------------------------------------------------------------------
			# RPi: Fix missing root mount in fstab: https://github.com/MichaIng/DietPi/issues/3511
			if ! grep -q '[[:blank:]]/[[:blank:]]' /etc/fstab; then

				G_WHIP_MSG '[WARNING] Refreshing /etc/fstab
\nYour system seems to be affected by a bug, introduced with DietPi v6.29, where /etc/fstab does not contain a root mount entry after running DietPi-Drive_Manager. We have fixed it and will now refresh your /etc/fstab with DietPi-Drive_Manager.
\nA backup is created, just in case you made manual changes.'
				G_BACKUP_FP /etc/fstab
				/boot/dietpi/dietpi-drive_manager 3

			fi

		elif (( $G_DIETPI_VERSION_SUB == 30 )); then

			#-------------------------------------------------------------------------------
			# Make userdata dir world-executable so service users don't need to be in dietpi group to access their data dir: https://github.com/MichaIng/DietPi/pull/3536#issuecomment-628515444
			[[ -d '/mnt/dietpi_userdata' ]] && G_EXEC chmod a+x /mnt/dietpi_userdata
			#-------------------------------------------------------------------------------
			# Assure /media exists to fulfil FHS, fix htpdate service startup and probably other issues: https://github.com/MichaIng/DietPi/issues/3558
			[[ -d '/media' ]] || G_EXEC mkdir /media
			#-------------------------------------------------------------------------------
			# All users are permitted to "ping" now without any further capabilities, hence remove them for security reasons: https://github.com/MichaIng/DietPi/commit/caec92e92e136a2f731f6d4c45db8463896fc80a
			local fp_ping=$(readlink -e "$(command -v ping)")
			if [[ $fp_ping ]]; then

				sysctl -p /etc/sysctl.d/dietpi.conf
				command -v getcap > /dev/null && [[ $(getcap "$fp_ping") ]] && setcap -r "$fp_ping"
				chmod a-s "$fp_ping"

			fi
			#-------------------------------------------------------------------------------
			# Fix default RPi3+ overclocking defaults: https://dietpi.com/phpbb/viewtopic.php?t=7804
			if [[ $G_HW_MODEL == 3 && $G_HW_MODEL_NAME == *'+'* ]]; then

				sed -i '/#arm_freq=/c\#arm_freq=1400' /boot/config.txt
				sed -i '/#sdram_freq=/c\#sdram_freq=500' /boot/config.txt

			fi
			#-------------------------------------------------------------------------------
			# Reinstalls
			#	Folding@Home: https://github.com/MichaIng/DietPi/pull/3546
			#	SqueezeLite: https://github.com/MichaIng/DietPi/issues/2386#issuecomment-651982127
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				# Reset QuiteRSS install state if the package has not actually been installed: https://github.com/MichaIng/DietPi/commit/49f960a7953f44e5571ff2dde68a93efca37ec03
				dpkg-query -s quiterss &> /dev/null || sed -i '/^aSOFTWARE_INSTALL_STATE\[22\]=2/d' /boot/dietpi/.installed

				if grep -q '^aSOFTWARE_INSTALL_STATE\[36\]=2' /boot/dietpi/.installed; then

					G_DIETPI-NOTIFY 2 'Preparing SqueezeLite update...'
					rm -Rfv /usr/bin/squeezelite* /etc/default/squeezelite
					[[ -f '/etc/systemd/system/squeezelite.service' ]] && G_CONFIG_INJECT 'User=' 'User=squeezelite' /etc/systemd/system/squeezelite.service '\[Service\]'
					echo 36 >> /var/tmp/dietpi/dietpi-update_reinstalls

				fi

				if grep -q '^aSOFTWARE_INSTALL_STATE\[2\]=2' /boot/dietpi/.installed; then

					G_DIETPI-NOTIFY 2 'Preparing Folding@Home update...'
					[[ -f '/lib/systemd/system/fahclient.service' ]] && rm /lib/systemd/system/fahclient.service
					[[ -f '/var/log/fahclient.log' ]] && rm /var/log/fahclient.log
					dpkg-query -s fahclient &> /dev/null && G_AGP fahclient
					echo 2 >> /var/tmp/dietpi/dietpi-update_reinstalls

				fi

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 31 )); then

			#-------------------------------------------------------------------------------
			# APT configs have been merged into a single file, contained in update archive
			rm -fv /etc/apt/apt.conf.d/{99-dietpi-norecommends,98-dietpi-no_translations,99-dietpi-forceconf}
			#-------------------------------------------------------------------------------
			[[ -f '/boot/config.txt' ]] && G_EXEC_DESC='Removing deprecated "max_usb_current" from config.txt' G_EXEC_NOHALT=1 G_EXEC sed -i '/^[[:blank:]#]*max_usb_current=/d' /boot/config.txt
			#-----------------------------------------------------------------------
			# Recreate /etc/sysctl.d/99-sysctl.conf -> ../sysctl.conf symlink if not existent: https://github.com/MichaIng/DietPi/issues/3003#issuecomment-669464255
			if [[ ! -L '/etc/sysctl.d/99-sysctl.conf' ]]; then

				[[ -e '/etc/sysctl.d/99-sysctl.conf' ]] && mv /etc/sysctl.d/99-sysctl.conf /etc/sysctl.conf
				ln -sf ../sysctl.conf /etc/sysctl.d/99-sysctl.conf

			fi
			#-------------------------------------------------------------------------------
			# DietPi-LetsEncrypt: Lighttpd: Rename HTTPS config files to new scheme: https://github.com/MichaIng/DietPi/pull/3734
			if [[ $G_DIETPI_INSTALL_STAGE == 2 && -f '/boot/dietpi/.dietpi-letsencrypt' && -d '/etc/lighttpd/conf-enabled' ]]; then

				local f='/etc/lighttpd/conf-enabled/letsencrypt.conf'
				if [[ -f $f && ! -L $f ]]; then
					mv -v "$f" /etc/lighttpd/conf-available/50-dietpi-https.conf
					lighty-enable-mod dietpi-https
				fi
				f='/etc/lighttpd/conf-enabled/redirect.conf'
				if [[ -f $f && ! -L $f ]]; then
					mv -v "$f" /etc/lighttpd/conf-available/98-dietpi-https_redirect.conf
					lighty-enable-mod dietpi-https_redirect
				fi
				f='/etc/lighttpd/conf-available/99-dietpi-hsts.conf'
				if [[ -f $f ]]; then
					mv -v "$f" "${f/99/98}"
					[[ -L ${f/available/enabled} ]] && { lighty-disable-mod dietpi-hsts; lighty-enable-mod dietpi-hsts; }
				fi

			fi
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 32 )); then

			#-------------------------------------------------------------------------------
			# Update config file names
			[[ -f '/etc/X11/xorg.conf.d/99-dietpi-dpms_off.conf' ]] && mv -v /etc/X11/xorg.conf.d/9{9-dietpi-dpms_off,8-dietpi-disable_dpms}.conf
			#-------------------------------------------------------------------------------
			# Transmission
			if (( $G_DIETPI_INSTALL_STAGE == 2 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[44\]=2' /boot/dietpi/.installed && [[ -f '/etc/systemd/system/transmission-daemon.service.d/dietpi-group.conf' ]] ; then

				G_DIETPI-NOTIFY 2 'Making "dietpi" the primary group for "debian-transmission" user instead of running the service as "dietpi" group'
				G_EXEC usermod -g dietpi -aG debian-transmission debian-transmission
				G_EXEC rm /etc/systemd/system/transmission-daemon.service.d/dietpi-group.conf
				G_EXEC rmdir --ignore-fail-on-non-empty /etc/systemd/system/transmission-daemon.service.d

			fi
			#-------------------------------------------------------------------------------
			# Tautulli: https://github.com/MichaIng/DietPi/pull/3784
			if (( $G_DIETPI_INSTALL_STAGE == 2 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[146\]=2' /boot/dietpi/.installed && [[ -d '/opt/plexpy' ]] ; then

				G_WHIP_MSG '[ INFO ] Renaming PlexPy to Tautulli
\nPlexPy has been renamed to Tautulli a while ago. To honour this, we will rename user, directories and service now accordingly:
 - Install/Git directory: /opt/tautulli
 - Data/Config directory: /mnt/dietpi_userdata/tautulli
 - systemd service name:  tautulli.service
 - systemd service user:  tautulli (group: tautulli)
\nAdditionally it will run now with Python 3 instead of Python 2. A Tautulli reinstall is done to apply these changes.'
				G_EXEC mv /opt/{plexpy,tautulli}
				[[ -d '/mnt/dietpi_userdata/plexpy' ]] && G_EXEC mv /mnt/dietpi_userdata/{plexpy,tautulli}
				[[ -f '/opt/tautulli/config.ini' ]] && G_EXEC mv /{opt,mnt/dietpi_userdata}/tautulli/config.ini
				G_EXEC sed -i 's|/opt/plexpy|/opt/tautulli|' /mnt/dietpi_userdata/tautulli/config.ini
				G_EXEC sed -i 's|/mnt/dietpi_userdata/plexpy|/mnt/dietpi_userdata/tautulli|' /mnt/dietpi_userdata/tautulli/config.ini
				[[ -f '/etc/systemd/system/plexpy.service' ]] && G_EXEC mv /etc/systemd/system/{plexpy,tautulli}.service
				[[ -d '/etc/systemd/system/plexpy.service.d' ]] && G_EXEC mv /etc/systemd/system/{plexpy,tautulli}.service.d
				getent passwd plexpy > /dev/null && G_EXEC userdel plexpy
				getent group plexpy > /dev/null && G_EXEC groupdel plexpy
				echo 146 >> /var/tmp/dietpi/dietpi-update_reinstalls

			fi
			#-------------------------------------------------------------------------------
			# Nextcloud + Lighttpd: https://dietpi.com/phpbb/viewtopic.php?p=27445#p27445
			if (( $G_DIETPI_INSTALL_STAGE == 2 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[114\]=2' /boot/dietpi/.installed && grep -q '^aSOFTWARE_INSTALL_STATE\[84\]=2' /boot/dietpi/.installed &&
				[[ -f '/etc/lighttpd/conf-available/99-dietpi-nextcloud.conf' ]] && grep -q opcache /etc/lighttpd/conf-available/99-dietpi-nextcloud.conf; then

				G_DIETPI-NOTIFY 2 'Removing obsolete directive from Lighttpd Nextcloud config file'
				G_EXEC sed -i '/opcache/d' /etc/lighttpd/conf-available/99-dietpi-nextcloud.conf
				for i in /etc/php/7.[234]/mods-available
				do

					[[ -d $i ]] || continue
					echo -e '; Nextcloud PHP settings\n; priority=98\napc.enable_cli=1\nopcache.enable=1\nopcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000\nopcache.memory_consumption=128\nopcache.save_comments=1\nopcache.revalidate_freq=1' > "$i/dietpi-nextcloud.ini"

				done
				G_EXEC_NOHALT=1 G_EXEC phpenmod dietpi-nextcloud

			fi
			#-------------------------------------------------------------------------------
			# Mosquitto reinstall: https://github.com/MichaIng/DietPi/issues/3042
			# Amiberry v3.3
			echo 108 123 >> /var/tmp/dietpi/dietpi-update_reinstalls
			#-------------------------------------------------------------------------------
			# Cuberite: https://github.com/MichaIng/DietPi/issues/3664
			if (( $G_DIETPI_INSTALL_STAGE == 2 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[52\]=2' /boot/dietpi/.installed && [[ ! -d '/mnt/dietpi_userdata/cuberite' ]]; then

				if [[ -d '/mnt/dietpi_userdata/cubrite' ]]; then

					G_WHIP_MSG '[ INFO ] Fixing typo in Cuberite install directory
\nThe install directory of Cuberite will be moved:
- /mnt/dietpi_userdata/cubrite > /mnt/dietpi_userdata/cuberite
\nFor this, it will be reinstalled. A backup is stored at:
- /mnt/dietpi_userdata/cuberite_bak'
					G_EXEC mv /mnt/dietpi_userdata/{cubrite,cuberite}
					G_EXEC cp -a /mnt/dietpi_userdata/cuberite{,_bak}
					echo 52 >> /var/tmp/dietpi/dietpi-update_reinstalls

				elif [[ -d '/etc/cubrite' ]]; then

					G_WHIP_MSG '[ INFO ] Moving Cuberite install directory
\nThe install directory of Cuberite will be moved:
- /etc/cubrite > /mnt/dietpi_userdata/cuberite
\nFor this, it will be reinstalled. A backup is stored at:
- /mnt/dietpi_userdata/cuberite_bak'
					G_EXEC mkdir -p /mnt/dietpi_userdata
					G_EXEC mv /etc/cubrite /mnt/dietpi_userdata/cuberite
					G_EXEC cp -a /mnt/dietpi_userdata/cuberite{,_bak}
					echo 52 >> /var/tmp/dietpi/dietpi-update_reinstalls

				fi

			fi
			#-------------------------------------------------------------------------------
			# TigerVNC + LXDE: https://github.com/MichaIng/DietPi/pull/3800
			(( $G_DIETPI_INSTALL_STAGE == 2 )) && grep -q '^aSOFTWARE_INSTALL_STATE\[28\]=2' /boot/dietpi/.installed && grep -q '^aSOFTWARE_INSTALL_STATE\[23\]=2' /boot/dietpi/.installed && G_AGI dbus-user-session
			#-------------------------------------------------------------------------------
			# Fail2Ban: https://github.com/MichaIng/DietPi/pull/3813
			[[ ! -f '/etc/fail2ban/jail.conf' ]] || sed -n '/^\[DEFAULT\]/,/^\[/p' /etc/fail2ban/jail.conf | grep -q '^[[:blank:]]*mode[[:blank:]]*=' || sed -i '/^\[DEFAULT\]/a\mode = normal' /etc/fail2ban/jail.conf
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 33 )); then

			#-------------------------------------------------------------------------------
			# Remove Tonido install flag
			if [[ -f '/boot/dietpi/.installed' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[134\]=2' /boot/dietpi/.installed
			then
				sed -i '/^aSOFTWARE_INSTALL_STATE\[134\]=2/d' /boot/dietpi/.installed
				# Add service to custom includes if it has not been excluded, since it has been removed from the static DietPi-Services list
				grep -q '^- tonido$' /boot/dietpi/.dietpi-services_include_exclude || G_CONFIG_INJECT '+ tonido' '+ tonido' /boot/dietpi/.dietpi-services_include_exclude
			fi
			#-------------------------------------------------------------------------------
			# Remove CloudPrint install flag
			[[ -f '/boot/dietpi/.installed' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[137\]=2' /boot/dietpi/.installed && sed -i '/^aSOFTWARE_INSTALL_STATE\[137\]=2/d' /boot/dietpi/.installed
			#-------------------------------------------------------------------------------
			# Remove DietPi-CloudShell install flag
			[[ -f '/boot/dietpi/.installed' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[62\]=2' /boot/dietpi/.installed && sed -i '/^aSOFTWARE_INSTALL_STATE\[62\]=2/d' /boot/dietpi/.installed
			#-------------------------------------------------------------------------------
			if [[ -f '/boot/dietpi/.installed' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[29\]=2' /boot/dietpi/.installed && ! dpkg-query -s xorgxrdp &> /dev/null
			then
				G_DIETPI-NOTIFY 2 'Installing xorgxrdp package to allow XRDP connections via "Xorg" method without VNC'
				[[ $G_DISTRO == 4 && $G_RASPBIAN != 1 ]] && cat << '_EOF_' > /etc/apt/preferences.d/dietpi-xrdp
Package: xrdp xorgxrdp
Pin: release n=stretch-backports
Pin-Priority: 500
_EOF_
				G_AGI xorgxrdp

				# Workaround for failing mouse and keyboard input: https://github.com/MichaIng/DietPi/issues/3022
				G_CONFIG_INJECT 'Option "CoreKeyboard"' '    Option "CoreKeyboard"' /etc/X11/xrdp/xorg.conf 'Driver "xrdpkeyb"'
				G_CONFIG_INJECT 'Option "CorePointer"' '    Option "CorePointer"' /etc/X11/xrdp/xorg.conf 'Driver "xrdpmouse"'
			fi
			#-------------------------------------------------------------------------------
			# Resolve Ampache permissions issue: https://dietpi.com/phpbb/viewtopic.php?p=29366#p29366
			[[ -f '/boot/dietpi/.installed' && -f '/var/www/ampache/config/ampache.cfg.php' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[40\]=2' /boot/dietpi/.installed && G_EXEC chown www-data /var/www/ampache/config/ampache.cfg.php
			#-------------------------------------------------------------------------------
			# RPi: Re-apply GPU memory split to disable VCSM if GPU memory is lower than 32 MiB
			if (( $G_HW_MODEL < 10 ))
			then
				local value=$G_HW_MEMORY_SIZE
				(( $value <= 1024 )) || value=1024
				local gpu_mem_current=$(sed -n "/^[[:blank:]]*gpu_mem_$value=/{s/^[^=]*=//p;q}" /boot/config.txt) # override setting
				[[ $gpu_mem_current ]] || gpu_mem_current=$(sed -n "/^[[:blank:]]*gpu_mem=/{s/^[^=]*=//p;q}" /boot/config.txt) # base setting
				[[ $gpu_mem_current ]] || gpu_mem_current=64 # default value
				(( $gpu_mem_current < 32 )) && /boot/dietpi/func/dietpi-set_hardware gpumemsplit $gpu_mem_current
			#-------------------------------------------------------------------------------
			# RPi CM 3+: Update USBridgeSig Ethernet driver via postinst kernel script, until it has been merged into official RPi kernel: https://github.com/allocom/USBridgeSig/tree/master/ethernet
				cat << '_EOF_' > /etc/kernel/postinst.d/dietpi-USBridgeSig
#!/bin/bash
# Only available for v7+
[[ $1 == *'-v7+' ]] || exit 0
# Only reasonable for USBridgeSig = CM 3+
grep -q '^Revision.*10.$' /proc/cpuinfo || exit 0
echo "[ INFO ] Updating ASIX AX88179 driver for kernel $1 with ARM-optimised build"
echo '[ INFO ] - by Allo: https://github.com/allocom/USBridgeSig/tree/master/ethernet'
echo '[ INFO ] Estimating required module layout...'
module_layout=$(modprobe --dump-modversions /lib/modules/$1/kernel/drivers/net/usb/asix.ko | mawk '/module_layout/{print $1;exit}') || exit 0
echo '[ INFO ] Downloading stable branch driver...'
if ! curl -#fL http://3.230.113.73:9011/Allocom/USBridgeSig/stable_rel/rpi-usbs-$1/ax88179_178a.ko -o /tmp/ax88179_178a.ko ||
	[[ $module_layout != $(modprobe --dump-modversions /tmp/ax88179_178a.ko | mawk '/module_layout/{print $1;exit}') ]]
then
	echo '[ INFO ] No matching stable branch driver found, trying master branch driver...'
	if ! curl -#fL http://3.230.113.73:9011/Allocom/USBridgeSig/rpi-usbs-$1/ax88179_178a.ko -o /tmp/ax88179_178a.ko ||
		[[ $module_layout != $(modprobe --dump-modversions /tmp/ax88179_178a.ko | mawk '/module_layout/{print $1;exit}') ]]
	then
		echo '[ INFO ] No matching driver found, cleaning up and aborting...'
		rm -fv /tmp/ax88179_178a.ko || :
		echo '[ INFO ] The default RPi kernel driver will be used instead, which might result in pops and ticks in your audio stream. If so, please try to rerun this script later:'
		echo " - /etc/kernel/postinst.d/dietpi-USBridgeSig $1"
		exit 0
	fi
fi
echo '[ INFO ] Installing driver...'
install -vpm 644 /tmp/ax88179_178a.ko /lib/modules/$1/kernel/drivers/net/usb || exit 0
echo '[ INFO ] Running depmod...'
depmod $1 || exit 0
echo '[ INFO ] All succeeded, cleaning up...'
rm -v /tmp/ax88179_178a.ko || exit 0
_EOF_
				chmod +x /etc/kernel/postinst.d/dietpi-USBridgeSig
				# Run for all installed v7+ kernel versions now
				for i in /lib/modules/*-v7+
				do
					[[ -d $i ]] || continue
					i=${i##*/}
					/etc/kernel/postinst.d/dietpi-USBridgeSig "$i"
				done
			#-------------------------------------------------------------------------------
			# ROCK Pi S: Fix/update Radxa APT repository
			elif (( $G_HW_MODEL == 73 ))
			then
				G_DIETPI-NOTIFY 2 'Repairing Radxa ROCK Pi S repository and marked packages'
				apt-key del 'C79E F8D1 49CF C9C0 418A  9A60 5761 288B 2B52 CC90'
				[[ -f '/etc/apt/sources.list.d/apt-radxa-com.list' ]] && rm -v /etc/apt/sources.list.d/apt-radxa-com.list
				G_EXEC eval "curl -sSfL https://apt.radxa.com/${G_DISTRO_NAME/bullseye/buster}-stable/public.key | gpg --dearmor -o /etc/apt/trusted.gpg.d/dietpi-radxa.gpg --yes"
				G_EXEC eval "echo -e 'deb https://apt.radxa.com/${G_DISTRO_NAME/bullseye/buster}-stable/ ${G_DISTRO_NAME/bullseye/buster} main\n#deb https://apt.radxa.com/${G_DISTRO_NAME/bullseye/buster}-testing/ ${G_DISTRO_NAME/bullseye/buster} main' > /etc/apt/sources.list.d/dietpi-radxa.list"
				if dpkg-query -s rockpis-rk-u-boot-latest &> /dev/null
				then
					G_EXEC apt-mark manual rockpis-rk-ubootimg
					G_EXEC apt-mark auto rockpis-rk-u-boot-latest
				fi
				if dpkg-query -s linux-4.4-rockpis-latest &> /dev/null
				then
					G_EXEC apt-mark auto linux-4.4-rockpis-latest
					G_AGI linux-4.4-rock-pi-s-latest
				fi
			#-------------------------------------------------------------------------------
			# Sparky SBC: Update Ethernet driver: https://github.com/sparky-sbc/sparky-test/tree/master/sparky-eth
			elif (( $G_HW_MODEL == 70 ))
			then
				G_DIETPI-NOTIFY 2 'Updating Sparky SBC Ethernet driver'
				G_EXEC curl -sSfL https://raw.githubusercontent.com/sparky-sbc/sparky-test/master/sparky-eth/ethernet.ko -o /lib/modules/3.10.38/kernel/drivers/net/ethernet/acts/ethernet.ko
			fi
			#-------------------------------------------------------------------------------
			# MineOS reinstall to migrate from supervisor to systemd unit: https://github.com/MichaIng/DietPi/pull/3904
			[[ -f '/etc/systemd/system/mineos.service' ]] || echo 53 >> /var/tmp/dietpi/dietpi-update_reinstalls
			#-------------------------------------------------------------------------------
			# Radarr reinstall to migrate to .NET version, available for non-ARMv6 with new v3: https://github.com/MichaIng/DietPi/issues/3943
			if [[ -f '/boot/dietpi/.installed' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[145\]=2' /boot/dietpi/.installed
			then
				G_DIETPI-NOTIFY 2 'Preparing Radarr reinstall to migrate to newest version'
				[[ -d '/opt/Radarr' ]] && G_EXEC rm -R /opt/Radarr
				[[ -d '/opt/radarr' ]] && G_EXEC rm -R /opt/radarr
				[[ -f '/mnt/dietpi_userdata/radarr/config.xml' ]] && G_CONFIG_INJECT '<Branch>' '  <Branch>master</Branch>' /mnt/dietpi_userdata/radarr/config.xml '<Config>'
				echo 145 >> /var/tmp/dietpi/dietpi-update_reinstalls
			fi
			#-------------------------------------------------------------------------------
			# OctoPrint reinstall to migrate to new PyPI-based install and apply permission fixes: https://github.com/MichaIng/DietPi/issues/3940
			if [[ -f '/boot/dietpi/.installed' ]] && grep -q '^aSOFTWARE_INSTALL_STATE\[153\]=2' /boot/dietpi/.installed
			then
				G_WHIP_MSG '[ INFO ] Preparing OctoPrint reinstall
\nThe internal updater of OctoPrint has changed, which does not work with the way OctoPrint was installed. We hence need to reinstall it to make the software updater, as well as plugin installs, functional.
\nNote that you likely need to reinstall plugins. We are especially sorry for users where this was required just after the last DietPi update already, due to Python 2 => Python 3 migration.
\nOctoPrint is now installed as service user local instance to:
 - /mnt/dietpi_userdata/octoprint/.local/
\nThe good news is that this is a long-term reliable method, so that we do not expect any further required changes.'
				if [[ -d '/root/.octoprint' && ! -d '/mnt/dietpi_userdata/octoprint/.octoprint' ]]
				then
					G_EXEC mkdir -p /mnt/dietpi_userdata/octoprint
					G_EXEC mv /{root,mnt/dietpi_userdata/octoprint}/.octoprint
				fi
				[[ -d '/opt/octoprint' ]] && G_EXEC rm -Rf /opt/octoprint
				# Beta 6.34.0+1
				[[ -f '/mnt/dietpi_userdata/octoprint/pip2' ]] && G_EXEC rm /mnt/dietpi_userdata/octoprint/pip2
				[[ -f '/mnt/dietpi_userdata/octoprint/pip3' ]] && G_EXEC rm /mnt/dietpi_userdata/octoprint/pip3
				[[ -f '/mnt/dietpi_userdata/octoprint/.octoprint/config.yaml' ]] && G_EXEC sed -i '/localPipCommand/d' /mnt/dietpi_userdata/octoprint/.octoprint/config.yaml
				# shellcheck disable=SC2046
				command -v pip2 > /dev/null && pip2 uninstall -y $(pip2 freeze | mawk '/[Oo]cto[Pp]rint/{print $1}') 2> /dev/null
				# shellcheck disable=SC2046
				command -v pip3 > /dev/null && pip3 uninstall -y $(pip3 freeze | mawk '/[Oo]cto[Pp]rint/{print $1}') 2> /dev/null
				echo 153 >> /var/tmp/dietpi/dietpi-update_reinstalls
			fi
			#-------------------------------------------------------------------------------
			# Webmin: Remove obsolete workaround: https://github.com/MichaIng/DietPi/issues/3810
			[[ -f '/etc/apt/apt.conf.d/98dietpi-webmin' ]] && rm /etc/apt/apt.conf.d/98dietpi-webmin
			#-------------------------------------------------------------------------------
			# Repair sound card setting, in case "-eq" got appended multiple times: https://github.com/MichaIng/DietPi/issues/3950
			if grep -q '^[[:blank:]]*CONFIG_SOUNDCARD=.*-eq-eq$' /boot/dietpi.txt
			then
				G_DIETPI-NOTIFY 2 'Repairing dietpi.txt sound card setting'
				local soundcard=$(sed -n '/^[[:blank:]]*CONFIG_SOUNDCARD=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)
				while [[ $soundcard == *'-eq' ]]; do soundcard=${soundcard%-eq}; done
				G_CONFIG_INJECT 'CONFIG_SOUNDCARD=' "CONFIG_SOUNDCARD=$soundcard-eq" /boot/dietpi.txt
			fi
			#-------------------------------------------------------------------------------
			# Migrating ALSA equalizer config to new location
			if [[ -f '/root/.alsaequal.bin' ]] && grep -q '^[[:blank:]]*CONFIG_SOUNDCARD=.*-eq$' /boot/dietpi.txt
			then
				G_DIETPI-NOTIFY 2 'Migrating ALSA equalizer config to new location'
				G_EXEC mkdir -p /var/lib/dietpi/dietpi-config
				G_EXEC mv /{root,var/lib/dietpi/dietpi-config}/.alsaequal.bin
				G_EXEC chmod 0775 /var/lib/dietpi/dietpi-config
				G_EXEC chmod 0664 /var/lib/dietpi/dietpi-config/.alsaequal.bin
				G_EXEC chown dietpi:dietpi /var/lib/dietpi/dietpi-config{,/.alsaequal.bin}
			fi
			#-------------------------------------------------------------------------------
			# Beta: Remove falsely created nyx config directory where a file should have been placed
			[[ -d '/root/.nyx/config' ]] && G_EXEC rm -R /root/.nyx/config
			#-------------------------------------------------------------------------------
			# Nextcloud: Apply 512 MiB PHP memory limit which is required to assure updater success and will else be treated as error with Nextcloud 21: https://github.com/nextcloud/server/commit/1995097cb8623b2447a2805a8e8e045c24203311
			for i in /etc/php/*/mods-available/dietpi-nextcloud.ini
			do
				[[ -f $i ]] || continue
				G_CONFIG_INJECT 'memory_limit[[:blank:]]*=' 'memory_limit=512M' "$i"
			done
			#-------------------------------------------------------------------------------

		elif (( $G_DIETPI_VERSION_SUB == 34 )); then

			#-------------------------------------------------------------------------------
			# Unbound: Merge dietpi-pihole.conf into dietpi.conf
			if [[ -f '/etc/unbound/unbound.conf.d/dietpi-pihole.conf' && -f '/etc/unbound/unbound.conf.d/dietpi.conf' ]]
			then
				G_DIETPI-NOTIFY 2 'Unbound: Merging dietpi-pihole.conf into dietpi.conf'
				local interface=$(mawk '/^[ \t]*interface:/{print $2;exit}' /etc/unbound/unbound.conf.d/dietpi-pihole.conf)
				local port=$(mawk '/^[ \t]*port:/{print $2;exit}' /etc/unbound/unbound.conf.d/dietpi-pihole.conf)
				G_CONFIG_INJECT 'interface:[[:blank:]]' "	interface: $interface" /etc/unbound/unbound.conf.d/dietpi.conf
				G_CONFIG_INJECT 'port:[[:blank:]]' "	port: $port" /etc/unbound/unbound.conf.d/dietpi.conf
				G_EXEC rm /etc/unbound/unbound.conf.d/dietpi-pihole.conf
			fi
			#-------------------------------------------------------------------------------
			# ReadyMedia: Fix database rebuild on service start
			[[ -f '/etc/systemd/system/minidlna.service' ]] && G_EXEC sed -i '/^ExecStart=/s/ -SR / -S -R /' /etc/systemd/system/minidlna.service
			#-------------------------------------------------------------------------------
			# https://github.com/jirka-h/haveged/pull/7 https://github.com/MichaIng/DietPi/issues/3689#issuecomment-678322767
			if [[ $G_DISTRO == 5 && $G_HW_ARCH == [23] && $G_HW_MODEL -gt 9 ]] && dpkg-query -s haveged &> /dev/null; then

				G_DIETPI-NOTIFY 2 'Upgrading haveged entropy daemon to fix an issue on ARM:'
				G_DIETPI-NOTIFY 2 ' - https://github.com/jirka-h/haveged/pull/7'
				G_EXEC curl -sSfLO "https://dietpi.com/downloads/binaries/buster/libhavege2_$G_HW_ARCH_NAME.deb"
				G_EXEC curl -sSfLO "https://dietpi.com/downloads/binaries/buster/haveged_$G_HW_ARCH_NAME.deb"
				G_AGI "./libhavege2_$G_HW_ARCH_NAME.deb" "./haveged_$G_HW_ARCH_NAME.deb"
				G_EXEC_NOHALT=1 G_EXEC rm "./libhavege2_$G_HW_ARCH_NAME.deb" "./haveged_$G_HW_ARCH_NAME.deb"

			fi
			#-------------------------------------------------------------------------------
			# Raspberry Pi Microsoft VS Code repo: https://github.com/MichaIng/DietPi/issues/4083
			[[ $G_HW_MODEL -le 9 && -f '/etc/apt/sources.list.d/vscode.list' ]] && { G_WHIP_BUTTON_OK_TEXT='Keep it' G_WHIP_BUTTON_CANCEL_TEXT='Remove it' G_WHIP_YESNO 'The Microsoft Visual Studio Code APT repository has been found on your system.
\nThis repository was added by the "raspberrypi-sys-mods" package from the Raspberry Pi Foundation, to support development around the new Raspberry Pi Pico.
\nIf you do no VS Code development, we suggest to remove this APT repository and its key from your system.' || G_EXEC rm -f /etc/apt/sources.list.d/vscode.list /etc/apt/trusted.gpg.d/microsoft.gpg /etc/apt/preferences.d/3rd_parties.pref; }
			#-------------------------------------------------------------------------------
			# Remove obsolete directory
			[[ -d '/var/lib/dietpi/dietpi-software/services' ]] && G_EXEC rmdir --ignore-fail-on-non-empty /var/lib/dietpi/dietpi-software/services
			#-------------------------------------------------------------------------------
			# Last subversion patch completed: Apply reinstalls
			if [[ -f '/var/tmp/dietpi/dietpi-update_reinstalls' ]]
			then
				# Coders NB: Assigning to array is not easily possible here since we need to split at newline AND space.
				# shellcheck disable=SC2046
				(( $G_DIETPI_INSTALL_STAGE == 2 )) && { /boot/dietpi/dietpi-software reinstall $(</var/tmp/dietpi/dietpi-update_reinstalls) || exit 1; }
				rm /var/tmp/dietpi/dietpi-update_reinstalls
			fi
			#-------------------------------------------------------------------------------

		fi
		: # Subversion patch finished, return "0"
	}

	#-------------------------------------------------------------------------------
	# Apply subversion patches incrementally
	# Store RC version "0" during incremental patching. DietPi-Update applies final RC version afterwards.
	G_DIETPI_VERSION_RC=0
	until (( $G_DIETPI_VERSION_SUB > 34 ))
	do
		G_DIETPI-NOTIFY 2 "Patching $G_DIETPI_VERSION_CORE.$G_DIETPI_VERSION_SUB to $G_DIETPI_VERSION_CORE.$(( $G_DIETPI_VERSION_SUB + 1 ))"
		Subversion_Patch || exit 1
		((G_DIETPI_VERSION_SUB++))
		# Save reached version info
		G_VERSIONDB_SAVE
	done
	#-------------------------------------------------------------------------------
	exit 0
	#-------------------------------------------------------------------------------
}
